@aerogel/plugin-local-first 0.1.2-next.823beb2779ebc4c5272f5e4e094cecc32cffa527 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -41,7 +41,7 @@ export declare const Cloud: Facade<CloudService>;
41
41
  export declare class CloudService extends _default {
42
42
  protected asyncLock: Semaphore;
43
43
  protected engine: Engine | null;
44
- protected pollingInterval: ReturnType<typeof setInterval> | null;
44
+ protected pollingInterval: NodeJS.Timeout | null;
45
45
  protected documentsCache: DocumentsCache | null;
46
46
  whenReady<T>(callback: () => T): Promise<T>;
47
47
  setup(modelUrlMappings?: WeakMap<SolidModelConstructor, Record<string, string>>): Promise<void>;
@@ -1297,12 +1297,12 @@ const I = Ne(yn), wn = {
1297
1297
  height: "1.2em"
1298
1298
  };
1299
1299
  function Mn(o, n) {
1300
- return p(), D("svg", wn, [...n[0] || (n[0] = [
1300
+ return p(), D("svg", wn, n[0] || (n[0] = [
1301
1301
  y("path", {
1302
1302
  fill: "currentColor",
1303
1303
  d: "m6 2l2-2h4l2 2h4v2H2V2zM3 6h14l-1 14H4zm5 2v10h1V8zm3 0v10h1V8z"
1304
1304
  }, null, -1)
1305
- ])]);
1305
+ ]));
1306
1306
  }
1307
1307
  const Cn = J({ name: "zondicons-trash", render: Mn }), rt = /* @__PURE__ */ H({
1308
1308
  __name: "AccountLoginModal",
@@ -1390,12 +1390,12 @@ In any case, Focus works 100% offline and you can connect your Solid POD later o
1390
1390
  height: "1.2em"
1391
1391
  };
1392
1392
  function kn(o, n) {
1393
- return p(), D("svg", Rn, [...n[0] || (n[0] = [
1393
+ return p(), D("svg", Rn, n[0] || (n[0] = [
1394
1394
  y("path", {
1395
1395
  fill: "currentColor",
1396
1396
  d: "M2.93 17.07A10 10 0 1 1 17.07 2.93A10 10 0 0 1 2.93 17.07m12.73-1.41A8 8 0 1 0 4.34 4.34a8 8 0 0 0 11.32 11.32M6.7 9.29L9 11.6l4.3-4.3l1.4 1.42L9 14.4l-3.7-3.7l1.4-1.42z"
1397
1397
  }, null, -1)
1398
- ])]);
1398
+ ]));
1399
1399
  }
1400
1400
  const Ln = J({ name: "zondicons-checkmark-outline", render: kn }), An = {
1401
1401
  viewBox: "0 0 24 24",
@@ -1403,12 +1403,12 @@ const Ln = J({ name: "zondicons-checkmark-outline", render: kn }), An = {
1403
1403
  height: "1.2em"
1404
1404
  };
1405
1405
  function Un(o, n) {
1406
- return p(), D("svg", An, [...n[0] || (n[0] = [
1406
+ return p(), D("svg", An, n[0] || (n[0] = [
1407
1407
  y("path", {
1408
1408
  fill: "currentColor",
1409
1409
  d: "M19.35 10.04A7.49 7.49 0 0 0 12 4C9.11 4 6.6 5.64 5.35 8.04A5.994 5.994 0 0 0 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5c0-2.64-2.05-4.78-4.65-4.96M14 13v4h-4v-4H7l5-5l5 5z"
1410
1410
  }, null, -1)
1411
- ])]);
1411
+ ]));
1412
1412
  }
1413
1413
  const En = J({ name: "ic-sharp-cloud-upload", render: Un }), In = {
1414
1414
  viewBox: "0 0 20 20",
@@ -1416,12 +1416,12 @@ const En = J({ name: "ic-sharp-cloud-upload", render: Un }), In = {
1416
1416
  height: "1.2em"
1417
1417
  };
1418
1418
  function zn(o, n) {
1419
- return p(), D("svg", In, [...n[0] || (n[0] = [
1419
+ return p(), D("svg", In, n[0] || (n[0] = [
1420
1420
  y("path", {
1421
1421
  fill: "currentColor",
1422
1422
  d: "M3.94 6.5L2.22 3.64l1.42-1.42L6.5 3.94c.52-.3 1.1-.54 1.7-.7L9 0h2l.8 3.24c.6.16 1.18.4 1.7.7l2.86-1.72l1.42 1.42l-1.72 2.86c.3.52.54 1.1.7 1.7L20 9v2l-3.24.8c-.16.6-.4 1.18-.7 1.7l1.72 2.86l-1.42 1.42l-2.86-1.72c-.52.3-1.1.54-1.7.7L11 20H9l-.8-3.24c-.6-.16-1.18-.4-1.7-.7l-2.86 1.72l-1.42-1.42l1.72-2.86c-.3-.52-.54-1.1-.7-1.7L0 11V9l3.24-.8c.16-.6.4-1.18.7-1.7M10 13a3 3 0 1 0 0-6a3 3 0 0 0 0 6"
1423
1423
  }, null, -1)
1424
- ])]);
1424
+ ]));
1425
1425
  }
1426
1426
  const at = J({ name: "zondicons-cog", render: zn }), Pn = {
1427
1427
  viewBox: "0 0 24 24",
@@ -1429,12 +1429,12 @@ const at = J({ name: "zondicons-cog", render: zn }), Pn = {
1429
1429
  height: "1.2em"
1430
1430
  };
1431
1431
  function On(o, n) {
1432
- return p(), D("svg", Pn, [...n[0] || (n[0] = [
1432
+ return p(), D("svg", Pn, n[0] || (n[0] = [
1433
1433
  y("path", {
1434
1434
  fill: "currentColor",
1435
1435
  d: "M5 21q-.825 0-1.412-.587T3 19V5q0-.825.588-1.412T5 3h6q.425 0 .713.288T12 4t-.288.713T11 5H5v14h6q.425 0 .713.288T12 20t-.288.713T11 21zm12.175-8H10q-.425 0-.712-.288T9 12t.288-.712T10 11h7.175L15.3 9.125q-.275-.275-.275-.675t.275-.7t.7-.313t.725.288L20.3 11.3q.3.3.3.7t-.3.7l-3.575 3.575q-.3.3-.712.288t-.713-.313q-.275-.3-.262-.712t.287-.688z"
1436
1436
  }, null, -1)
1437
- ])]);
1437
+ ]));
1438
1438
  }
1439
1439
  const qn = J({ name: "material-symbols-logout-rounded", render: On }), Tn = {
1440
1440
  viewBox: "0 0 20 20",
@@ -1442,12 +1442,12 @@ const qn = J({ name: "material-symbols-logout-rounded", render: On }), Tn = {
1442
1442
  height: "1.2em"
1443
1443
  };
1444
1444
  function _n(o, n) {
1445
- return p(), D("svg", Tn, [...n[0] || (n[0] = [
1445
+ return p(), D("svg", Tn, n[0] || (n[0] = [
1446
1446
  y("path", {
1447
1447
  fill: "currentColor",
1448
1448
  d: "M10 3v2a5 5 0 0 0-3.54 8.54l-1.41 1.41A7 7 0 0 1 10 3m4.95 2.05A7 7 0 0 1 10 17v-2a5 5 0 0 0 3.54-8.54zM10 20l-4-4l4-4zm0-12V0l4 4z"
1449
1449
  }, null, -1)
1450
- ])]);
1450
+ ]));
1451
1451
  }
1452
1452
  const te = J({ name: "zondicons-refresh", render: _n }), Wn = {
1453
1453
  viewBox: "0 0 24 24",
@@ -1455,12 +1455,12 @@ const te = J({ name: "zondicons-refresh", render: _n }), Wn = {
1455
1455
  height: "1.2em"
1456
1456
  };
1457
1457
  function Nn(o, n) {
1458
- return p(), D("svg", Wn, [...n[0] || (n[0] = [
1458
+ return p(), D("svg", Wn, n[0] || (n[0] = [
1459
1459
  y("path", {
1460
1460
  fill: "currentColor",
1461
1461
  d: "M6 6h12v12H6z"
1462
1462
  }, null, -1)
1463
- ])]);
1463
+ ]));
1464
1464
  }
1465
1465
  const Jn = J({ name: "ic-baseline-stop", render: Nn }), xn = {
1466
1466
  viewBox: "0 0 512 512",
@@ -1468,12 +1468,12 @@ const Jn = J({ name: "ic-baseline-stop", render: Nn }), xn = {
1468
1468
  height: "1.2em"
1469
1469
  };
1470
1470
  function Bn(o, n) {
1471
- return p(), D("svg", xn, [...n[0] || (n[0] = [
1471
+ return p(), D("svg", xn, n[0] || (n[0] = [
1472
1472
  y("path", {
1473
1473
  fill: "currentColor",
1474
1474
  d: "M449.07 399.08L278.64 82.58c-12.08-22.44-44.26-22.44-56.35 0L51.87 399.08A32 32 0 0 0 80 446.25h340.89a32 32 0 0 0 28.18-47.17m-198.6-1.83a20 20 0 1 1 20-20a20 20 0 0 1-20 20m21.72-201.15l-5.74 122a16 16 0 0 1-32 0l-5.74-121.95a21.73 21.73 0 0 1 21.5-22.69h.21a21.74 21.74 0 0 1 21.73 22.7Z"
1475
1475
  }, null, -1)
1476
- ])]);
1476
+ ]));
1477
1477
  }
1478
1478
  const ne = J({ name: "ion-warning", render: Bn }), jn = { class: "relative flex items-center rounded-md bg-gray-100 p-4 pr-12" }, Fn = { class: "flex flex-col overflow-hidden" }, Vn = { class: "font-semibold" }, Hn = { class: "px-2" }, Kn = {
1479
1479
  key: 0,
@@ -1 +1 @@
1
- {"version":3,"file":"aerogel-plugin-local-first.js","sources":["../src/lib/inference.ts","../src/lib/SyncQueue.ts","../src/lib/mirroring.ts","../src/jobs/Backup.ts","../src/lib/utils.ts","../src/jobs/mixins/LoadsChildren.ts","../src/jobs/mixins/LoadsTypeIndex.ts","../src/jobs/mixins/TracksLocalModels.ts","../src/jobs/Migrate.ts","../src/jobs/Sync.ts","../src/services/Cloud.state.ts","../src/services/Cloud.ts","../src/components/AccountLoginModal.vue","../src/components/settings/PurgeData.vue","../src/components/settings/index.ts","../src/components/AccountModal.vue","../src/components/AccountLoggedIn.vue","../src/components/AccountLoggedOut.vue","../src/components/Account.vue","../src/index.ts"],"sourcesContent":["import {\n Metadata,\n Operation,\n SolidACLAuthorization,\n SolidContainer,\n SolidContainsRelation,\n SolidDocument,\n SolidIsContainedByRelation,\n SolidModel,\n SolidResource,\n isContainerClass,\n isSolidDocumentRelation,\n} from 'soukai-solid';\nimport { arrayFilter, isInstanceOf } from '@noeldemartin/utils';\n\nimport type { SolidContainerConstructor, SolidModelConstructor } from 'soukai-solid';\n\nconst containerRelations: WeakMap<typeof SolidModel, string[]> = new WeakMap();\nconst sameDocumentRelations: WeakMap<typeof SolidModel, string[]> = new WeakMap();\n\nexport function getContainerRegisteredClasses(modelClass: SolidContainerConstructor): SolidModelConstructor[] {\n return arrayFilter(\n getContainerRelations(modelClass).map((relation) => {\n const relatedClass = modelClass.instance().requireRelation<SolidContainsRelation>(relation).relatedClass;\n\n if (isContainerClass(relatedClass)) {\n return false;\n }\n\n return relatedClass;\n }),\n );\n}\n\nexport function getContainerRelations(modelClass: typeof SolidModel): string[] {\n if (!containerRelations.has(modelClass)) {\n containerRelations.set(\n modelClass,\n modelClass.relations.filter((relation) => {\n if (SolidModel.reservedRelations.includes(relation)) {\n return false;\n }\n\n const relationInstance = modelClass.instance().requireRelation(relation);\n\n return relationInstance instanceof SolidContainsRelation;\n }),\n );\n }\n\n return containerRelations.get(modelClass) ?? [];\n}\n\nexport function getContainedModels(model: SolidContainer): SolidModel[] {\n const relations = getContainerRelations(model.static());\n\n return relations.reduce(\n (models, relation) => models.concat(model.getRelationModels(relation) ?? []),\n [] as SolidModel[],\n );\n}\n\nexport function getRelatedClasses(modelClass: SolidModelConstructor): SolidModelConstructor[] {\n const relatedClasses = new Set<SolidModelConstructor>();\n const instance = modelClass.instance();\n\n relatedClasses.add(modelClass);\n\n for (const relation of modelClass.relations) {\n if (modelClass.reservedRelations.includes(relation)) {\n continue;\n }\n\n relatedClasses.add(instance.requireRelation(relation).relatedClass);\n }\n\n return [...relatedClasses.values()];\n}\n\nexport function getRelatedAppModels(model: SolidModel): SolidModel[] {\n return model\n .getRelatedModels()\n .filter(\n (related) =>\n !isInstanceOf(related, SolidACLAuthorization) &&\n !isInstanceOf(related, SolidDocument) &&\n !isInstanceOf(related, SolidResource) &&\n !isInstanceOf(related, Metadata) &&\n !isInstanceOf(related, Operation) &&\n related.static() !== SolidContainer,\n );\n}\n\nexport function getSameDocumentRelations(modelClass: typeof SolidModel): string[] {\n if (!sameDocumentRelations.has(modelClass)) {\n sameDocumentRelations.set(\n modelClass,\n modelClass.relations.filter((relation) => {\n if (SolidModel.reservedRelations.includes(relation)) {\n return false;\n }\n\n const relationInstance = modelClass.instance().requireRelation(relation);\n\n return isSolidDocumentRelation(relationInstance) && relationInstance.useSameDocument;\n }),\n );\n }\n\n return sameDocumentRelations.get(modelClass) ?? [];\n}\n\nexport function isDirtyOrHasDirtyChildren(model: SolidModel): boolean {\n if (model.isDirty()) {\n return true;\n }\n\n if (!(model instanceof SolidContainer)) {\n return false;\n }\n\n const relationHasDirtyModels = (relation: string) => {\n return model.getRelationModels(relation)?.some((relatedModel) => isDirtyOrHasDirtyChildren(relatedModel));\n };\n\n return getContainerRelations(model.static()).some(relationHasDirtyModels);\n}\n\nexport async function loadAppRelations(model: SolidModel, onError?: (error: unknown) => void): Promise<void> {\n const builtInRelations = ['authorizations', 'metadata', 'operations', 'tombstone'];\n\n let updated;\n\n do {\n updated = false;\n\n const relatedModels = getRelatedAppModels(model);\n\n for (const relatedModel of relatedModels) {\n for (const relation of relatedModel.static('relations')) {\n if (\n builtInRelations.includes(relation) ||\n relatedModel.isRelationLoaded(relation) ||\n relatedModel.getRelation(relation) instanceof SolidIsContainedByRelation\n ) {\n continue;\n }\n\n try {\n await relatedModel.loadRelation(relation);\n\n updated = true;\n } catch (error) {\n if (!onError) {\n throw error;\n }\n\n onError(error);\n }\n }\n }\n } while (updated);\n}\n","import { after, arrayRemove, facade, required } from '@noeldemartin/utils';\nimport { App } from '@aerogel/core';\nimport { type SolidModel, isContainer } from 'soukai-solid';\n\nimport { getContainedModels } from '@aerogel/plugin-local-first/lib/inference';\n\nconst Cloud = required(() => App.service('$cloud'));\n\nclass SyncQueue {\n\n private models: Set<SolidModel> = new Set();\n private promises: Promise<unknown>[] = [];\n\n public push(model: SolidModel): void {\n this.models.add(model);\n this.syncAfter(after({ seconds: 1 }));\n }\n\n public clear(models?: SolidModel[]): void {\n if (!models) {\n this.models = new Set();\n\n return;\n }\n\n for (const model of models) {\n this.models.delete(model);\n }\n }\n\n protected async syncAfter<T = void>(operationOrPromise: Promise<T> | (() => Promise<T>)): Promise<T> {\n const promise = typeof operationOrPromise === 'function' ? operationOrPromise() : operationOrPromise;\n\n this.promises.push(promise);\n\n promise.then(() => arrayRemove(this.promises, promise));\n\n if (this.promises.length === 1) {\n this.schedule();\n }\n\n return promise as Promise<T>;\n }\n\n private schedule(): void {\n Promise.all(this.promises)\n .then(() => after())\n .then(() => {\n if (this.promises.length !== 0) {\n this.schedule();\n\n return;\n }\n\n const models = this.consume();\n\n if (models.length === 0) {\n return;\n }\n\n Cloud.syncIfOnline(models);\n });\n }\n\n private consume(): SolidModel[] {\n const models: SolidModel[] = [];\n const children: Set<SolidModel> = new Set();\n\n for (const model of this.models) {\n if (!isContainer(model)) {\n continue;\n }\n\n this.models.delete(model);\n getContainedModels(model).forEach((child) => children.add(child));\n models.push(model);\n }\n\n for (const model of this.models) {\n this.models.delete(model);\n\n if (children.has(model)) {\n continue;\n }\n\n models.push(model);\n }\n\n return models;\n }\n\n}\n\nexport default facade(SyncQueue);\n","import { bootModels } from 'soukai';\nimport { fail, requireUrlParentDirectory, required, tap, urlResolveDirectory, urlRoute } from '@noeldemartin/utils';\nimport { App } from '@aerogel/core';\nimport { getTrackedModels, trackModelsCollection as trackSoukaiModelsCollection } from '@aerogel/plugin-soukai';\nimport { Solid } from '@aerogel/plugin-solid';\nimport { PropertyOperation, SolidContainer, Tombstone, isContainerClass } from 'soukai-solid';\nimport type {\n Operation,\n SolidContainsRelation,\n SolidModel,\n SolidModelConstructor,\n SolidSchemaDefinition,\n} from 'soukai-solid';\nimport type { ObjectsMap } from '@noeldemartin/utils';\nimport type { Attributes } from 'soukai';\n\nimport SyncQueue from '@aerogel/plugin-local-first/lib/SyncQueue';\nimport { getContainerRelations, getRelatedAppModels } from '@aerogel/plugin-local-first/lib/inference';\n\ninterface CloneOptions {\n clean?: boolean;\n}\n\nconst Cloud = required(() => App.service('$cloud'));\nconst remoteClasses: WeakMap<SolidModelConstructor, SolidModelConstructor> = new WeakMap();\nconst localClasses: WeakMap<SolidModelConstructor, SolidModelConstructor> = new WeakMap();\nconst cloneConstructors: WeakMap<SolidModelConstructor, [typeof SolidModel, typeof SolidModel][]> = new WeakMap();\n\nfunction getRelationClasses(modelClass: typeof SolidModel, visited?: Set<typeof SolidModel>): Set<typeof SolidModel> {\n visited ??= new Set();\n\n if (!visited.has(modelClass)) {\n visited.add(modelClass);\n\n for (const relation of modelClass.relations) {\n getRelationClasses(modelClass.instance().requireRelation(relation).relatedClass, visited);\n }\n }\n\n return visited;\n}\n\nfunction cleanRemoteModelClone(remoteModel: SolidModel): void {\n const relatedModels = remoteModel.getRelatedModels().concat([remoteModel]);\n\n for (const relatedModel of relatedModels) {\n relatedModel.cleanDirty(true);\n }\n}\n\nfunction fixRemoteModelClone(remoteModel: SolidModel): void {\n const relatedModels = getRelatedAppModels(remoteModel).concat([remoteModel]);\n\n for (const relatedModel of relatedModels) {\n if (!relatedModel.operations || relatedModel.operations.length === 0) {\n continue;\n }\n\n const operations = (relatedModel.operations ?? []).filter((operation) => {\n return (\n !(operation instanceof PropertyOperation) ||\n !relatedModel.ignoreRdfPropertyHistory(operation.property, true)\n );\n });\n\n if (!operations.some((operation) => !operation.isInception(relatedModel))) {\n relatedModel.setRelationModels('operations', []);\n\n continue;\n }\n\n relatedModel.setRelationModels('operations', operations);\n }\n}\n\nexport async function createRemoteModel(localModel: SolidModel): Promise<void> {\n Cloud.setState({\n localModelUpdates: {\n ...Cloud.localModelUpdates,\n [localModel.url]: 1,\n },\n });\n\n if (isRegisteredModelClass(localModel.static())) {\n await trackModelsCollection(localModel.static(), requireUrlParentDirectory(localModel.url));\n }\n\n if (Cloud.autoPush && Cloud.ready && !Cloud.syncing) {\n SyncQueue.push(localModel);\n }\n}\n\nexport function createRemoteContainer(remoteModel: SolidModel, localModels: ObjectsMap<SolidModel>): SolidContainer {\n const RemoteContainer = getRemoteClass(SolidContainer);\n const path = Cloud.registeredModels.find(\n ({ modelClass: registeredModelClass }) => registeredModelClass === remoteModel.static(),\n )?.path;\n\n return new RemoteContainer({\n url: getRemoteContainersCollection(getLocalModel(remoteModel, localModels).static(), path),\n });\n}\n\nexport async function trackModelsCollection(modelClass: SolidModelConstructor, collection: string): Promise<void> {\n if (Cloud.modelCollections[modelClass.modelName]?.includes(collection)) {\n return;\n }\n\n Cloud.setState('modelCollections', {\n ...Cloud.modelCollections,\n [modelClass.modelName]: (Cloud.modelCollections[modelClass.modelName] ?? []).concat(collection),\n });\n\n await trackSoukaiModelsCollection(modelClass, collection);\n}\n\nexport async function updateRemoteModel(localModel: SolidModel): Promise<void> {\n if (ignoreModelUpdates(localModel)) {\n return;\n }\n\n const modelUpdates = Cloud.localModelUpdates[localModel.url] ?? 0;\n\n Cloud.setState({\n localModelUpdates: {\n ...Cloud.localModelUpdates,\n [localModel.url]: localModel.isSoftDeleted() ? 1 : modelUpdates + 1,\n },\n });\n\n await Cloud.getDocumentsCache().forget(\n requireUrlParentDirectory(localModel.requireDocumentUrl()),\n localModel.requireDocumentUrl(),\n );\n\n if (Cloud.autoPush && Cloud.ready && !Cloud.syncing) {\n SyncQueue.push(localModel);\n }\n}\n\nexport function clearLocalModelUpdates(syncedModelUrls: Set<string>, documentsWithErrors?: Set<string>): void {\n const localModelUpdates = {} as Record<string, number>;\n const syncedModelUrlsArray = Array.from(syncedModelUrls);\n\n for (const [url, count] of Object.entries(Cloud.localModelUpdates)) {\n const documentUrl = urlRoute(url);\n const wasSynced =\n syncedModelUrls.has(url) ||\n syncedModelUrlsArray.some((modelUrl) => modelUrl.endsWith('/') && url.startsWith(modelUrl));\n\n if (wasSynced && !documentsWithErrors?.has(documentUrl)) {\n continue;\n }\n\n localModelUpdates[url] = count;\n }\n\n Cloud.setState({ localModelUpdates });\n}\n\nexport function cloneLocalModel(localModel: SolidModel, options: CloneOptions = {}): SolidModel {\n const constructors = Array.from(new Set(getRelatedAppModels(localModel).map((model) => model.static()))).map(\n (localClass) => [localClass, getRemoteClass(localClass)] as [typeof SolidModel, typeof SolidModel],\n );\n\n return tap(localModel.clone({ constructors }), (model) => {\n fixRemoteModelClone(model);\n\n options.clean && cleanRemoteModelClone(model);\n });\n}\n\nexport function cloneRemoteModel(remoteModel: SolidModel): SolidModel {\n return remoteModel.clone({ constructors: getCloneConstructors(remoteModel) });\n}\n\nexport async function completeRemoteModels(\n localModels: SolidModel[],\n remoteModels: SolidModel[],\n documentsWithErrors: Set<string>,\n): Promise<SolidModel[]> {\n const RemoteTombstone = getRemoteClass(Tombstone);\n const remoteModelUrls = remoteModels.map((remoteModel) => remoteModel.url);\n const missingModelDocumentUrls = localModels\n .filter((localModel) => !remoteModelUrls.includes(localModel.url))\n .map((localModel) => localModel.requireDocumentUrl())\n .filter((documentUrl) => !documentsWithErrors.has(documentUrl));\n const tombstones = await RemoteTombstone.all({ $in: missingModelDocumentUrls });\n\n return remoteModels.concat(tombstones);\n}\n\nexport function ignoreModelUpdates(localModel: SolidModel): boolean {\n const documentModels = localModel.getDocumentModels();\n const documentOperations = documentModels.flatMap(\n (model) => model.operations?.map((operation) => [model, operation] as [SolidModel, Operation]) ?? [],\n );\n\n return !documentOperations.some(([model, operation]) => {\n if (operation.date.getTime() !== model.metadata?.updatedAt?.getTime()) {\n return false;\n }\n\n if (!(operation instanceof PropertyOperation)) {\n return true;\n }\n\n return !model.ignoreRdfPropertyHistory(operation.property, true);\n });\n}\n\nexport function getCloneConstructors(model: SolidModel): [typeof SolidModel, typeof SolidModel][] {\n const modelClass = model.static();\n\n if (!cloneConstructors.has(modelClass)) {\n const constructors = Array.from(getRelationClasses(modelClass))\n .map((otherClass) =>\n isRemoteModelClass(otherClass)\n ? [otherClass, getLocalClass(otherClass)]\n : [otherClass, getRemoteClass(otherClass)])\n .map(([a, b]) => [\n [a, b] as [typeof SolidModel, typeof SolidModel],\n [b, a] as [typeof SolidModel, typeof SolidModel],\n ])\n .flat();\n\n for (const constructor of constructors) {\n cloneConstructors.set(constructor[0], constructors);\n }\n }\n\n return required(cloneConstructors.get(modelClass));\n}\n\nexport function getLocalModel(remoteModel: SolidModel, localModels: ObjectsMap<SolidModel>): SolidModel {\n return localModels.get(remoteModel.url) ?? cloneRemoteModel(remoteModel);\n}\n\nexport function getLocalModels(): SolidModel[] {\n return [...Cloud.registeredModels]\n .map(({ modelClass }) => getTrackedModels(modelClass, { includeSoftDeleted: true }))\n .flat();\n}\n\nexport function getSchemaMigrations(): Map<SolidModelConstructor, SolidModelConstructor | SolidSchemaDefinition> {\n return Cloud.schemaMigrations;\n}\n\nexport function clearSchemaMigrations(): void {\n Cloud.schemaMigrations.clear();\n}\n\nexport function getSchemaMigration(\n modelClass: SolidModelConstructor,\n): SolidModelConstructor | SolidSchemaDefinition | undefined {\n return Cloud.schemaMigrations.get(modelClass);\n}\n\nexport function getRemoteClass<T extends SolidModelConstructor>(localClass: T): T {\n return (remoteClasses.get(localClass) as T) ?? makeRemoteClass(localClass);\n}\n\nexport function getRemoteContainersCollection(modelClass: SolidModelConstructor, path?: string): string {\n const rootStorage = Solid.requireUser().storageUrls[0];\n const containedClass =\n isContainerClass(modelClass) &&\n getContainerRelations(modelClass)\n .map((relation) => {\n const relatedClass = modelClass\n .instance()\n .requireRelation<SolidContainsRelation>(relation).relatedClass;\n\n if (isContainerClass(relatedClass)) {\n return null;\n }\n\n return relatedClass;\n })\n .filter(Boolean)[0];\n\n path ??= `/${(containedClass || modelClass).modelName.toLowerCase()}s/`;\n\n return urlResolveDirectory((path.startsWith('/') ? rootStorage.slice(0, -1) : rootStorage) + path);\n}\n\nexport function getRemoteModel(localModel: SolidModel, remoteModels: ObjectsMap<SolidModel>): SolidModel {\n return remoteModels.get(localModel.url) ?? cloneLocalModel(localModel);\n}\n\nexport function isRegisteredModel(model: SolidModel): boolean {\n for (const { modelClass } of Cloud.registeredModels) {\n const models = getTrackedModels(modelClass);\n\n if (models.some((registeredModel) => registeredModel.url === model.url)) {\n return true;\n }\n }\n\n return false;\n}\n\nexport function isRemoteModel(model: SolidModel): boolean {\n return isRemoteModelClass(model.static());\n}\n\nexport function isRemoteModelClass(modelClass: typeof SolidModel): boolean {\n return localClasses.has(modelClass);\n}\n\nexport function isLocalModel(model: SolidModel): boolean {\n return !isRemoteModel(model);\n}\n\nexport function isRegisteredModelClass(modelClass: SolidModelConstructor): boolean {\n return Cloud.registeredModels.some(({ modelClass: registeredModelClass }) => registeredModelClass === modelClass);\n}\n\nexport function makeRemoteClass<T extends SolidModelConstructor>(localClass: T): T {\n const LocalClass = localClass as typeof SolidModel;\n const withLocalHistoryConfig = (modelClass: typeof SolidModel, operation: () => unknown) => {\n modelClass.timestamps = LocalClass.timestamps;\n modelClass.history = LocalClass.history;\n\n operation();\n\n modelClass.timestamps = [];\n modelClass.history = false;\n };\n const RemoteClass = class extends LocalClass {\n\n public static override timestamps = false;\n public static override history = false;\n\n protected override initialize(attributes: Attributes, exists: boolean): void {\n withLocalHistoryConfig(this._proxy.static(), () => super.initialize(attributes, exists));\n }\n\n protected override initializeRelations(): void {\n super.initializeRelations();\n\n for (const relation of Object.values(this._relations)) {\n relation.relatedClass = getRemoteClass(relation.relatedClass);\n }\n }\n\n public override fixMalformedAttributes(): void {\n withLocalHistoryConfig(this.static(), () => super.fixMalformedAttributes());\n }\n \n } as unknown as T;\n\n LocalClass.on('schema-updated', async (schema) => {\n await RemoteClass.updateSchema({\n ...schema,\n timestamps: false,\n history: false,\n });\n });\n\n localClass.ensureBooted();\n bootModels({ [`Remote${localClass.modelName}`]: RemoteClass });\n App.service('$cloud') && Cloud.getEngine() && RemoteClass.setEngine(Cloud.requireEngine());\n\n remoteClasses.set(LocalClass, RemoteClass);\n localClasses.set(RemoteClass, LocalClass);\n\n return RemoteClass;\n}\n\nexport function getLocalClass<T extends SolidModelConstructor>(remoteClass: T): T {\n return (localClasses.get(remoteClass) as T) ?? fail(`Couldn't find local class for ${remoteClass.modelName}`);\n}\n","import { Job } from '@aerogel/core';\nimport { requireEngine } from 'soukai';\nimport { requireUrlParentDirectory } from '@noeldemartin/utils';\nimport { ignoreModelsCollection, trackModelsCollection } from '@aerogel/plugin-soukai';\nimport { Solid } from '@aerogel/plugin-solid';\nimport type { EngineDocument, IndexedDBEngine } from 'soukai';\nimport type { SolidModelConstructor } from 'soukai-solid';\n\ninterface Migration {\n modelClass: SolidModelConstructor;\n local: string;\n remote: string;\n}\n\nexport default class Backup extends Job {\n\n private urlMigrations: Migration[] = [];\n private collectionMigrations: Migration[] = [];\n\n public migrateUrl(modelClass: SolidModelConstructor, local: string, remote: string): void {\n this.urlMigrations.push({\n modelClass,\n local,\n remote,\n });\n }\n\n public migrateCollection(modelClass: SolidModelConstructor, local: string, remote: string): void {\n this.collectionMigrations.push({\n modelClass,\n local,\n remote,\n });\n }\n\n protected async run(): Promise<void> {\n const engine = requireEngine<IndexedDBEngine>();\n const collections = await engine.getCollections();\n const droppedCollections = new Set<string>();\n\n for (const collection of collections) {\n const documents = await engine.readMany(collection);\n\n for (const [localUrl, document] of Object.entries(documents)) {\n const remoteUrl = this.replaceUrl(localUrl);\n\n await engine.create(\n requireUrlParentDirectory(remoteUrl),\n this.replaceDocumentUrls(document),\n remoteUrl,\n );\n\n await engine.delete(collection, localUrl);\n }\n }\n\n for (const { modelClass, remote } of this.urlMigrations) {\n trackModelsCollection(modelClass, requireUrlParentDirectory(remote));\n }\n\n for (const { modelClass, local, remote } of this.collectionMigrations) {\n const solidCollections = Object.assign({}, Solid.collections);\n const filteredCollections = (Solid.collections[modelClass.modelName] ?? []).filter(\n (collection) => !local.startsWith(collection),\n );\n\n ignoreModelsCollection(modelClass, local);\n trackModelsCollection(modelClass, remote);\n\n for (const localCollection of Solid.collections[modelClass.modelName] ?? []) {\n const remoteCollection = this.replaceUrl(localCollection);\n\n if (remoteCollection !== localCollection) {\n ignoreModelsCollection(modelClass, localCollection);\n trackModelsCollection(modelClass, remoteCollection);\n }\n }\n\n Solid.collections = solidCollections;\n\n collections\n .filter((collection) => local.startsWith(collection))\n .forEach((collection) => droppedCollections.add(collection));\n\n if (filteredCollections.length > 0) {\n solidCollections[modelClass.modelName] = filteredCollections;\n } else {\n delete solidCollections[modelClass.modelName];\n }\n }\n\n await engine.dropCollections(Array.from(droppedCollections));\n }\n\n protected replaceDocumentUrls(document: EngineDocument): EngineDocument {\n for (const [key, value] of Object.entries(document)) {\n if (key === '@id' && typeof value === 'string') {\n document[key] = this.replaceUrl(value);\n\n continue;\n }\n\n if (typeof value !== 'object' || value === null) {\n continue;\n }\n\n document[key] = this.replaceDocumentUrls(value as EngineDocument);\n }\n\n return document;\n }\n\n protected replaceUrl(url: string): string {\n for (const { local, remote } of this.urlMigrations) {\n if (!url.startsWith(local)) {\n continue;\n }\n\n return url.replace(local, remote);\n }\n\n for (const { local, remote } of this.collectionMigrations) {\n if (!url.startsWith(local)) {\n continue;\n }\n\n return url.replace(local, remote);\n }\n\n return url;\n }\n\n}\n","export function mapFromArray<K, V>(items: [K, V][]): Map<K, V> {\n const itemsMap = new Map();\n\n for (const [key, value] of items) {\n itemsMap.set(key, value);\n }\n\n return itemsMap;\n}\n\nexport function lazy<T>(getter: () => Promise<T>): () => Promise<T> {\n const result: { value?: T } = {};\n\n return async () => {\n if (!('value' in result)) {\n result.value = await getter();\n }\n\n return result.value as T;\n };\n}\n","import { arrayChunk, arrayFrom, isInstanceOf, map, requireUrlParentDirectory, required } from '@noeldemartin/utils';\nimport { DocumentNotFound, type EngineDocument } from 'soukai';\nimport { Tombstone } from 'soukai-solid';\nimport type { JobStatus } from '@aerogel/core';\nimport type { ObjectsMap } from '@noeldemartin/utils';\nimport type { SolidContainer, SolidContainsRelation, SolidDocument, SolidModel } from 'soukai-solid';\n\nimport { isLocalModel, isRemoteModel } from '@aerogel/plugin-local-first/lib/mirroring';\nimport { getContainerRelations } from '@aerogel/plugin-local-first/lib/inference';\nimport { lazy } from '@aerogel/plugin-local-first/lib/utils';\n\nexport interface ResourceJobStatus extends JobStatus {\n documentUrl?: string;\n children?: ResourceJobStatus[];\n}\n\nexport default class LoadsChildren {\n\n declare protected localModels?: ObjectsMap<SolidModel>;\n\n protected async loadContainedModels(\n container: SolidContainer,\n options: {\n ignoreTombstones?: boolean;\n status?: ResourceJobStatus;\n updateProgress?: (update?: () => unknown) => Promise<void>;\n onDocumentLoaded?: () => unknown;\n onDocumentError?: (error: unknown) => unknown;\n onDocumentRead?: (document: SolidDocument) => unknown;\n onDocumentIgnored?: (document: SolidDocument) => unknown;\n } = {},\n ): Promise<SolidModel[]> {\n if (isLocalModel(container)) {\n const children = [];\n\n for (const relation of getContainerRelations(container.static())) {\n const relationModels =\n (await container.loadRelationIfUnloaded<SolidModel | SolidModel[] | null>(relation)) ?? [];\n\n children.push(...arrayFrom(relationModels));\n }\n\n return children;\n }\n\n const children: Record<string, SolidModel[]> = {};\n const tombstones: Tombstone[] = [];\n const resourceUrlChunks = arrayChunk(container.resourceUrls, 10);\n const statusChildren = resourceUrlChunks.flat().map((url) => ({\n documentUrl: url,\n completed: false,\n }));\n const statusChildrenMap = map(statusChildren, 'documentUrl');\n const updateProgress = options.updateProgress ?? ((operation) => Promise.resolve(operation?.()));\n\n if (options.status) {\n options.status.children = statusChildren;\n }\n\n for (const resourceUrls of resourceUrlChunks) {\n await Promise.all(\n resourceUrls.map(async (resourceUrl) => {\n if (\n container.resources.some(\n (resource) =>\n resource.url === resourceUrl &&\n resource.types.some((type) =>\n type.startsWith('http://www.w3.org/ns/iana/media-types/image/')),\n )\n ) {\n return;\n }\n\n const { children: documentChildren, tombstones: documentTombstones } =\n await this.loadDocumentChildren(container, resourceUrl, options);\n\n tombstones.push(...documentTombstones);\n\n for (const [relation, documentModels] of Object.entries(documentChildren)) {\n const relationChildren = (children[relation] ??= []);\n\n relationChildren.push(...documentModels);\n }\n\n if (resourceUrl.endsWith('/')) {\n return;\n }\n\n await updateProgress(() => {\n required(statusChildrenMap.get(resourceUrl)).completed = true;\n });\n\n await options.onDocumentLoaded?.();\n }),\n );\n }\n\n for (const [relation, relationModels] of Object.entries(children)) {\n container.setRelationModels(relation, relationModels);\n }\n\n const childrenArray = options.ignoreTombstones\n ? Object.values(children).flat()\n : Object.values(children).flat().concat(tombstones);\n\n await updateProgress(() => {\n if (!options.status) {\n return;\n }\n\n options.status.children = childrenArray.map((child) => {\n return required(statusChildrenMap.get(child.requireDocumentUrl()));\n });\n });\n\n return childrenArray;\n }\n\n protected async loadContainedDocuments(\n container: SolidContainer,\n options: {\n status?: ResourceJobStatus;\n updateProgress?: (update?: () => unknown) => Promise<void>;\n onDocumentLoaded?: () => unknown;\n onDocumentError?: (error: unknown) => unknown;\n onDocumentRead?: (document: SolidDocument) => unknown;\n } = {},\n ): Promise<Record<string, EngineDocument>> {\n if (!isRemoteModel(container)) {\n throw Error('Cannot get contained models from local model');\n }\n\n const engineDocuments: Record<string, EngineDocument> = {};\n const remoteEngine = container.requireEngine();\n const resourceUrlChunks = arrayChunk(container.resourceUrls, 10);\n const statusChildren = resourceUrlChunks.flat().map((url) => ({\n documentUrl: url,\n completed: false,\n }));\n const statusChildrenMap = map(statusChildren, 'documentUrl');\n const updateProgress = options.updateProgress ?? ((operation) => Promise.resolve(operation?.()));\n\n if (options.status) {\n options.status.children = statusChildren;\n }\n\n for (const resourceUrls of resourceUrlChunks) {\n await Promise.all(\n resourceUrls.map(async (resourceUrl) => {\n if (\n !resourceUrl ||\n resourceUrl.endsWith('/') ||\n container.resources.some(\n (resource) =>\n resource.url === resourceUrl &&\n resource.types.some((type) =>\n type.startsWith('http://www.w3.org/ns/iana/media-types/image/')),\n )\n ) {\n await updateProgress(() => {\n required(statusChildrenMap.get(resourceUrl)).completed = true;\n });\n\n return;\n }\n\n const document = container.documents.find(({ url }) => url === resourceUrl);\n\n try {\n engineDocuments[resourceUrl] = await remoteEngine.readOne(container.url, resourceUrl);\n } catch (error) {\n if (!options.onDocumentError) {\n throw error;\n }\n\n await options.onDocumentError?.(error);\n }\n\n if (document) {\n await options.onDocumentRead?.(document);\n }\n\n await updateProgress(() => {\n required(statusChildrenMap.get(resourceUrl)).completed = true;\n });\n\n await options.onDocumentLoaded?.();\n }),\n );\n }\n\n return engineDocuments;\n }\n\n private async loadDocumentChildren(\n container: SolidContainer,\n documentUrl: string,\n options: {\n onDocumentError?: (error: unknown) => unknown;\n onDocumentRead?: (document: SolidDocument) => unknown;\n onDocumentIgnored?: (document: SolidDocument) => unknown;\n } = {},\n ): Promise<{ children: Record<string, SolidModel[]>; tombstones: Tombstone[] }> {\n return this.loadDocumentChildrenFromRemote(container, documentUrl, options);\n }\n\n private async loadDocumentChildrenFromRemote(\n container: SolidContainer,\n documentUrl: string,\n options: {\n onDocumentError?: (error: unknown) => unknown;\n onDocumentRead?: (document: SolidDocument) => unknown;\n onDocumentIgnored?: (document: SolidDocument) => unknown;\n } = {},\n ): Promise<{ children: Record<string, SolidModel[]>; tombstones: Tombstone[] }> {\n const children: Record<string, SolidModel[]> = {};\n const tombstones: Tombstone[] = [];\n const readDocument = lazy(async () => {\n try {\n const documentModel = container.documents.find((document) => document.url === documentUrl);\n const document = await container\n .requireEngine()\n .readOne(requireUrlParentDirectory(documentUrl), documentUrl);\n const documentTombstones = await Tombstone.createManyFromEngineDocuments({\n [documentUrl]: document,\n });\n\n tombstones.push(...documentTombstones);\n\n if (documentModel) {\n options.onDocumentRead?.(documentModel);\n }\n\n return document;\n } catch (error) {\n if (isInstanceOf(error, DocumentNotFound)) {\n return null;\n }\n\n if (!options.onDocumentError) {\n throw error;\n }\n\n options.onDocumentError(error);\n\n return null;\n }\n });\n\n let found = false;\n\n for (const relation of getContainerRelations(container.static())) {\n const relationInstance = container.requireRelation<SolidContainsRelation>(relation);\n\n if (relationInstance.loaded) {\n children[relation] = relationInstance.getLoadedModels();\n\n continue;\n }\n\n const document = await readDocument();\n\n if (!document) {\n continue;\n }\n\n try {\n const documentChildren = await relationInstance.relatedClass.createManyFromEngineDocuments({\n [documentUrl]: document,\n });\n\n children[relation] = documentChildren;\n\n found ||= documentChildren.length > 0;\n } catch (error) {\n if (!options.onDocumentError) {\n throw error;\n }\n\n options.onDocumentError(error);\n }\n }\n\n if (!found && options.onDocumentIgnored) {\n const documentModel = container.documents.find((document) => document.url === documentUrl);\n\n documentModel && (await options.onDocumentIgnored(documentModel));\n }\n\n return { children, tombstones };\n }\n\n}\n","import { Solid } from '@aerogel/plugin-solid';\nimport type { SolidTypeIndex } from 'soukai-solid';\nimport type { SolidUserProfile } from '@noeldemartin/solid-utils';\n\nconst typeIndexes: WeakMap<SolidUserProfile, SolidTypeIndex | null> = new WeakMap();\n\nexport default class LoadsTypeIndex {\n\n protected async loadTypeIndex(options?: { create?: false; fresh?: boolean }): Promise<SolidTypeIndex | null>;\n protected async loadTypeIndex(options?: { create?: true; fresh?: boolean }): Promise<SolidTypeIndex>;\n protected async loadTypeIndex(options: { create?: boolean; fresh?: boolean } = {}): Promise<SolidTypeIndex | null> {\n const user = Solid.requireUser();\n\n if (options.fresh || !typeIndexes.has(user)) {\n typeIndexes.set(user, await Solid.findPrivateTypeIndex({ fresh: options.fresh }));\n }\n\n if (options.create && !typeIndexes.get(user)) {\n typeIndexes.set(user, await Solid.findOrCreatePrivateTypeIndex());\n }\n\n return typeIndexes.get(user) ?? null;\n }\n\n}\n","import type { ObjectsMap } from '@noeldemartin/utils';\nimport type { SolidModel } from 'soukai-solid';\n\nimport { getRelatedAppModels, loadAppRelations } from '@aerogel/plugin-local-first/lib/inference';\n\nexport default class TracksLocalModels {\n\n declare protected localModels: ObjectsMap<SolidModel>;\n\n protected async indexLocalModels(models: SolidModel[]): Promise<void> {\n for (const localModel of models) {\n await this.addLocalModel(localModel);\n }\n }\n\n protected async addLocalModel(localModel: SolidModel): Promise<void> {\n if (this.localModels.hasKey(localModel.url)) {\n return;\n }\n\n this.localModels.add(localModel);\n\n await loadAppRelations(localModel);\n\n for (const relatedModel of getRelatedAppModels(localModel)) {\n await this.addLocalModel(relatedModel);\n }\n }\n\n}\n","import { PropertyOperation, isContainer } from 'soukai-solid';\nimport { Job } from '@aerogel/core';\nimport { isInstanceOf, map, mixed, objectMap, tap } from '@noeldemartin/utils';\nimport type { JobListener, JobStatus } from '@aerogel/core';\nimport type { Nullable } from '@noeldemartin/utils';\nimport type { SolidModel, SolidTypeIndex } from 'soukai-solid';\n\nimport {\n clearSchemaMigrations,\n getRemoteClass,\n getSchemaMigration,\n getSchemaMigrations,\n} from '@aerogel/plugin-local-first/lib/mirroring';\nimport { getContainerRegisteredClasses } from '@aerogel/plugin-local-first/lib/inference';\n\nimport LoadsChildren from './mixins/LoadsChildren';\nimport LoadsTypeIndex from './mixins/LoadsTypeIndex';\nimport TracksLocalModels from './mixins/TracksLocalModels';\n\nconst BaseJob = Job as typeof Job<JobListener, MigrateJobStatus, MigrateJobStatus>;\n\nexport interface MigrateJobStatus extends JobStatus {\n children?: MigrateModelJobStatus[];\n}\n\nexport interface MigrateModelJobStatus extends JobStatus {\n modelUrl: string;\n children?: MigrateModelJobStatus[];\n}\n\nexport default class Migrate extends mixed(BaseJob, [LoadsChildren, LoadsTypeIndex, TracksLocalModels]) {\n\n public static restore(status: MigrateJobStatus): Migrate {\n return tap(new Migrate(), (job) => {\n job.status = status;\n });\n }\n\n constructor() {\n super();\n\n this.localModels = map([], 'url');\n }\n\n protected _models?: SolidModel[];\n\n public get models(): SolidModel[] | undefined {\n return this._models;\n }\n\n public set models(models: SolidModel[] | undefined) {\n if (!models) {\n delete this._models;\n\n this.localModels = map([], 'url');\n\n return;\n }\n\n const childrenStatus = objectMap(this.status.children ?? [], 'modelUrl');\n\n this._models = models;\n this.localModels = map([], 'url');\n this.status.children = models.map(\n (model) =>\n childrenStatus[model.url] ?? {\n modelUrl: model.url,\n completed: false,\n },\n );\n }\n\n protected async run(): Promise<void> {\n if (!this.models) {\n throw new Error('Cant start migration without models');\n }\n\n await this.indexLocalModels(this.models);\n\n const modelStatuses = this.status.children ?? [];\n const typeIndex = await this.loadTypeIndex();\n\n for (const modelStatus of modelStatuses) {\n const model = this.models.find(({ url }) => modelStatus.modelUrl === url);\n\n if (!model || modelStatus.completed) {\n continue;\n }\n\n await this.migrateRegisteredModel(model, modelStatus, typeIndex);\n await this.updateProgress(() => (modelStatus.completed = true));\n }\n\n for (const [modelClass, schema] of getSchemaMigrations()) {\n await modelClass.updateSchema(schema);\n }\n\n clearSchemaMigrations();\n }\n\n protected async migrateRegisteredModel(\n model: SolidModel,\n status: MigrateModelJobStatus,\n typeIndex?: Nullable<SolidTypeIndex>,\n ): Promise<void> {\n await this.migrate(model, status);\n\n if (!isContainer(model)) {\n return;\n }\n\n const registeredClasses = getContainerRegisteredClasses(model.static());\n const registration = typeIndex?.registrations.find(({ instanceContainer }) => instanceContainer === model.url);\n\n if (!typeIndex || !registration || registeredClasses.length === 0) {\n return;\n }\n\n registration.setAttribute(\n 'forClass',\n registeredClasses\n .map((modelClass) => getSchemaMigration(modelClass)?.rdfsClasses ?? modelClass.rdfsClass)\n .flat(),\n );\n\n await typeIndex.save();\n }\n\n protected async migrate(localModel: SolidModel, status: MigrateModelJobStatus): Promise<void> {\n this.assertNotCancelled();\n\n await this.migrateChildren(localModel, status);\n\n const schema = getSchemaMigration(localModel.static());\n\n if (!schema) {\n return;\n }\n\n const remoteModel = await getRemoteClass(localModel.static()).find(localModel.url);\n const migratedModel = await remoteModel?.migrateSchema(schema);\n\n await localModel.migrateSchema(schema, {\n mintOperationUrl: (operation) => {\n return migratedModel?.operations?.find((migratedOperation) => {\n if (\n !isInstanceOf(operation, PropertyOperation) ||\n !isInstanceOf(migratedOperation, PropertyOperation)\n ) {\n return false;\n }\n\n return (\n operation.property === migratedOperation.property &&\n operation.date.getTime() === migratedOperation.date.getTime()\n );\n })?.url;\n },\n });\n }\n\n protected async migrateChildren(localModel: SolidModel, status: MigrateModelJobStatus): Promise<void> {\n if (!isContainer(localModel)) {\n return;\n }\n\n const children = await this.loadContainedModels(localModel, { ignoreTombstones: true });\n\n status.children ??= children.map((child) => ({\n modelUrl: child.url,\n completed: false,\n }));\n\n for (const childStatus of status.children) {\n const child = children.find(({ url }) => childStatus.modelUrl === url);\n\n if (!child || childStatus.completed) {\n continue;\n }\n\n await this.migrate(child, childStatus);\n await this.updateProgress(() => (childStatus.completed = true));\n }\n }\n\n}\n","import {\n arrayWithout,\n isInstanceOf,\n map,\n mixed,\n requireUrlParentDirectory,\n required,\n round,\n toString,\n urlRoute,\n} from '@noeldemartin/utils';\nimport { App, Errors, Job } from '@aerogel/core';\nimport { DocumentNotFound, InvalidModelAttributes, requireBootedModel, requireEngine } from 'soukai';\nimport { MalformedSolidDocumentError } from '@noeldemartin/solid-utils';\nimport { Solid } from '@aerogel/plugin-solid';\nimport { SolidContainer, SolidModel, Tombstone, isContainer, isContainerClass } from 'soukai-solid';\nimport type { ObjectsMap } from '@noeldemartin/utils';\nimport type { JobListener, JobStatus } from '@aerogel/core';\nimport type { SolidContainsRelation, SolidEngine, SolidModelConstructor, SolidTypeIndex } from 'soukai-solid';\n\nimport {\n clearLocalModelUpdates,\n cloneLocalModel,\n cloneRemoteModel,\n completeRemoteModels,\n createRemoteContainer,\n getCloneConstructors,\n getLocalModel,\n getLocalModels,\n getRemoteClass,\n getRemoteModel,\n isRegisteredModel,\n isRemoteModel,\n trackModelsCollection,\n} from '@aerogel/plugin-local-first/lib/mirroring';\nimport {\n getContainerRegisteredClasses,\n getContainerRelations,\n getRelatedAppModels,\n isDirtyOrHasDirtyChildren,\n loadAppRelations,\n} from '@aerogel/plugin-local-first/lib/inference';\n\nimport LoadsChildren from './mixins/LoadsChildren';\nimport LoadsTypeIndex from './mixins/LoadsTypeIndex';\nimport TracksLocalModels from './mixins/TracksLocalModels';\nimport type { ResourceJobStatus } from './mixins/LoadsChildren';\n\nconst Cloud = required(() => App.service('$cloud'));\nconst BaseJob = Job as typeof Job<JobListener, SyncJobStatus, SyncJobStatus>;\n\ninterface SyncJobStatus extends JobStatus {\n root: true;\n children: [SyncPullJobStatus, JobStatus];\n}\n\ninterface SyncPullJobStatus extends JobStatus {\n children?: ResourceJobStatus[];\n}\n\nfunction isRootStatus(status?: JobStatus): status is SyncJobStatus {\n return !!status && 'root' in status;\n}\n\nexport default class Sync extends mixed(BaseJob, [LoadsChildren, LoadsTypeIndex, TracksLocalModels]) {\n\n public readonly documentsWithErrors: Set<string>;\n protected models?: SolidModel[];\n protected dirtyRemoteModels?: SolidModel[];\n protected rootLocalModels: SolidModel[];\n protected tombstones: ObjectsMap<Tombstone>;\n protected syncedModelUrls: Set<string>;\n protected documentsModifiedAt: Record<string, Date>;\n protected screenLock: Promise<void | { release(): Promise<void> }> | null = null;\n protected override localModels: ObjectsMap<SolidModel>;\n\n constructor(models?: SolidModel[]) {\n super();\n\n this.documentsWithErrors = new Set();\n this.models = models;\n this.rootLocalModels = [];\n this.localModels = map([], 'url');\n this.tombstones = map([], 'resourceUrl');\n this.syncedModelUrls = new Set();\n this.documentsModifiedAt = {};\n }\n\n protected async run(): Promise<void> {\n const engine = Solid.requireAuthenticator().engine as SolidEngine;\n const updateDocumentDate = (url: string, { headers }: { headers?: Headers }, fallbackDate?: Date) => {\n const date = headers?.get('last-modified') ?? fallbackDate;\n\n if (!date || url.endsWith('/')) {\n return;\n }\n\n this.documentsModifiedAt[url] = new Date(date);\n };\n const clearListener = engine.listeners.add({\n onDocumentRead: (url, metadata) => updateDocumentDate(url, metadata),\n onDocumentUpdated: (url, metadata) => updateDocumentDate(url, metadata, new Date()),\n });\n\n try {\n this.lockScreen();\n this.rootLocalModels = this.models ?? getLocalModels();\n\n engine.setConfig({ cachesDocuments: true, persistentCache: Cloud.getDocumentsCache() });\n\n await this.indexLocalModels(this.rootLocalModels);\n await this.pullChanges();\n await this.pushChanges();\n } finally {\n engine.clearCache();\n engine.setConfig({ cachesDocuments: false, persistentCache: undefined });\n\n this.releaseScreen();\n clearListener();\n }\n }\n\n protected lockScreen(): void {\n const typedNavigator = navigator as {\n wakeLock?: { request(type?: 'screen'): Promise<{ release(): Promise<void> }> };\n };\n\n if (!typedNavigator.wakeLock) {\n return;\n }\n\n try {\n this.screenLock = typedNavigator.wakeLock.request('screen').catch((error) => {\n Errors.reportDevelopmentError(error, 'Could not request screen wake lock');\n });\n } catch (error) {\n Errors.reportDevelopmentError(error, 'Could not request screen wake lock');\n }\n }\n\n protected releaseScreen(): void {\n if (!this.screenLock) {\n return;\n }\n\n this.screenLock.then((lock) => lock?.release());\n this.screenLock = null;\n }\n\n protected override getInitialStatus(): SyncJobStatus {\n return {\n root: true,\n completed: false,\n children: [{ completed: false }, { completed: false }],\n };\n }\n\n protected override calculateCurrentProgress(status?: JobStatus): number {\n status ??= this.status;\n\n if (isRootStatus(status)) {\n return round(\n this.calculateCurrentProgress(status.children[0]) * 0.9 +\n this.calculateCurrentProgress(status.children[1]) * 0.1,\n 2,\n );\n }\n\n return super.calculateCurrentProgress(status);\n }\n\n private async pullChanges(): Promise<void> {\n const remoteModelsArray = this.models\n ? await this.fetchRemoteModelsForLocal(this.models)\n : await this.fetchRemoteModels();\n const remoteModels = map(remoteModelsArray, (model) => {\n if (model instanceof Tombstone) {\n return model.resourceUrl;\n }\n\n return model.url;\n });\n\n this.dirtyRemoteModels = await this.synchronizeModels(remoteModels);\n\n await this.updateProgress((status) => (status.children[0].completed = true));\n }\n\n private async pushChanges(): Promise<void> {\n const localDocuments = new Set(this.localModels.getItems().map((model) => model.getDocumentUrl()));\n const remoteModels = this.dirtyRemoteModels ?? [];\n const childrenStatus = (this.status.children[1].children = remoteModels.map(() => ({ completed: false })));\n\n for (let index = 0; index < remoteModels.length; index++) {\n const remoteModel = remoteModels[index] as SolidModel;\n const childStatus = childrenStatus[index] as JobStatus;\n\n if (remoteModel.isSoftDeleted()) {\n remoteModel.enableHistory();\n remoteModel.enableTombstone();\n\n await remoteModel.forceDelete();\n await this.updateProgress(() => (childStatus.completed = true));\n\n this.syncedModelUrls.add(remoteModel.url ?? remoteModel.getDeletedPrimaryKey());\n\n continue;\n }\n\n await this.saveModelAndRelated(remoteModel, childStatus);\n await this.updateTypeRegistrations(remoteModel);\n await this.updateProgress(() => (childStatus.completed = true));\n }\n\n const documentsCache = Cloud.getDocumentsCache();\n const tombstoneDocuments = map(this.tombstones.getItems(), (tombstone) => tombstone.requireDocumentUrl());\n\n for (const [documentUrl, modifiedAt] of Object.entries(this.documentsModifiedAt)) {\n if (tombstoneDocuments.hasKey(documentUrl)) {\n const tombstone = tombstoneDocuments.require(documentUrl);\n\n await documentsCache.remember(requireUrlParentDirectory(documentUrl), documentUrl, modifiedAt, {\n tombstone: {\n url: tombstone.url,\n resourceUrl: tombstone.resourceUrl,\n },\n });\n\n continue;\n }\n\n if (localDocuments.has(documentUrl)) {\n await documentsCache.remember(requireUrlParentDirectory(documentUrl), documentUrl, modifiedAt);\n\n continue;\n }\n }\n\n clearLocalModelUpdates(this.syncedModelUrls, this.documentsWithErrors);\n\n await this.updateProgress((status) => (status.children[1].completed = true));\n }\n\n private async fetchRemoteModels(): Promise<SolidModel[]> {\n const pullStatus = this.status.children[0];\n const typeIndex = await this.loadTypeIndex({ fresh: true });\n\n if (!typeIndex) {\n return [];\n }\n\n const remoteModels: SolidModel[] = [];\n const registrations = this.getTypeRegistrations(typeIndex);\n\n pullStatus.children = registrations.map(() => ({ completed: false }));\n\n for (let index = 0; index < registrations.length; index++) {\n const status = required(pullStatus.children?.[index]);\n const { registration, registeredModel } = required(registrations[index]);\n const remoteClass = getRemoteClass(registeredModel.modelClass);\n\n if (!registration.instanceContainer) {\n continue;\n }\n\n Cloud.rootModelCollections[registeredModel.modelClass.modelName] ??= registration.instanceContainer;\n\n if (isContainerClass(remoteClass)) {\n await trackModelsCollection(\n registeredModel.modelClass,\n requireUrlParentDirectory(registration.instanceContainer),\n );\n\n const container = await remoteClass.find(registration.instanceContainer);\n\n if (container) {\n await this.loadChildren(container, status);\n\n remoteModels.push(container);\n }\n\n await this.updateProgress(() => (status.completed = true));\n\n continue;\n }\n\n const containerModels = await this.fetchRemoteModelsFromContainer(\n status,\n registeredModel.modelClass,\n remoteClass,\n registration.instanceContainer,\n );\n\n remoteModels.push(...containerModels);\n\n await this.updateProgress(() => (status.completed = true));\n }\n\n for (const remoteModel of remoteModels) {\n await loadAppRelations(remoteModel, (error) => this.handleDocumentError(error));\n }\n\n return completeRemoteModels(this.rootLocalModels, remoteModels, this.documentsWithErrors);\n }\n\n private async fetchRemoteModelsFromContainer(\n status: ResourceJobStatus,\n localClass: SolidModelConstructor,\n remoteClass: SolidModelConstructor,\n containerUrl: string,\n ): Promise<SolidModel[]> {\n const container = await getRemoteClass(SolidContainer).find(containerUrl);\n\n if (!container) {\n return [];\n }\n\n status.children = container.resourceUrls.map(() => ({ completed: false }));\n\n const documents = await this.loadContainedDocuments(container, {\n status,\n updateProgress: (update) => this.updateProgress(update),\n onDocumentError: (error) => this.handleDocumentError(error),\n onDocumentRead: (document) => {\n if (document.url.endsWith('/') || !document.updatedAt || document.url in this.documentsModifiedAt) {\n return;\n }\n\n this.documentsModifiedAt[document.url] = document.updatedAt;\n },\n onDocumentLoaded: async () => {\n this.assertNotCancelled();\n\n await this.updateProgress();\n },\n });\n\n const remoteModels = await remoteClass.createManyFromEngineDocuments(documents);\n const tombstones = await Tombstone.createManyFromEngineDocuments(documents);\n const documentsCache = Cloud.getDocumentsCache();\n const foundDocuments = new Set(remoteModels.map((model) => model.requireDocumentUrl()));\n\n for (const tombstone of tombstones) {\n this.tombstones.add(tombstone);\n foundDocuments.add(tombstone.requireDocumentUrl());\n }\n\n for (const document of container.documents) {\n if (!document.updatedAt) {\n continue;\n }\n\n if (foundDocuments.has(document.url)) {\n continue;\n }\n\n await documentsCache.remember(requireUrlParentDirectory(document.url), document.url, document.updatedAt);\n\n const engine = requireEngine();\n\n try {\n await engine.readOne(requireUrlParentDirectory(document.url), document.url);\n } catch (error) {\n if (!isInstanceOf(error, DocumentNotFound)) {\n throw error;\n }\n\n // TODO this is causing some pretty nasty bugs!!\n await engine.create(requireUrlParentDirectory(document.url), {}, document.url);\n }\n }\n\n if (remoteModels.length > 0) {\n await trackModelsCollection(localClass, containerUrl);\n }\n\n for (let index = 0; index < container.resourceUrls.length; index++) {\n const resourceUrl = container.resourceUrls[index];\n\n if (!resourceUrl?.endsWith('/')) {\n continue;\n }\n\n const childModels = await this.fetchRemoteModelsFromContainer(\n required(status.children?.[index]),\n localClass,\n remoteClass,\n resourceUrl,\n );\n\n remoteModels.push(...childModels);\n\n await this.updateProgress();\n }\n\n await this.updateProgress(() => (status.completed = true));\n\n return remoteModels;\n }\n\n private async fetchRemoteModelsForLocal(models: SolidModel[]): Promise<SolidModel[]> {\n const remoteModels = [] as SolidModel[];\n const statusChildren = (this.status.children[0].children = models.map(() => ({ completed: false })));\n\n for (let index = 0; index < models.length; index++) {\n await this.ignoringDocumentErrors(async () => {\n const localModel = models[index] as SolidModel;\n const childStatus = statusChildren[index] as JobStatus;\n const remoteModel = await getRemoteClass(localModel.static()).find(localModel.url);\n\n if (!remoteModel) {\n await this.updateProgress(() => (childStatus.completed = true));\n\n return;\n }\n\n isContainer(remoteModel) && (await this.loadChildren(remoteModel, childStatus));\n\n remoteModels.push(remoteModel);\n\n await this.updateProgress(() => (childStatus.completed = true));\n });\n }\n\n for (const remoteModel of remoteModels) {\n await loadAppRelations(remoteModel, (error) => this.handleDocumentError(error));\n }\n\n return completeRemoteModels(models, remoteModels, this.documentsWithErrors);\n }\n\n private getTypeRegistrations(typeIndex: SolidTypeIndex) {\n const processedContainerUrls = new Set();\n const registeredModels = [...Cloud.registeredModels].map(({ modelClass }) => {\n const registeredChildren = isContainerClass(modelClass) ? getContainerRegisteredClasses(modelClass) : [];\n\n return {\n modelClass,\n rdfsClasses:\n registeredChildren.length > 0\n ? registeredChildren.map((childrenClass) => childrenClass.rdfsClasses).flat()\n : modelClass.rdfsClasses,\n };\n });\n const registrations = typeIndex.registrations\n .map((registration) => {\n const registeredModel = registeredModels.find(\n ({ rdfsClasses }) =>\n !!registration.instanceContainer &&\n rdfsClasses.some((rdfsClass) => registration.forClass.includes(rdfsClass)),\n );\n\n if (\n !registeredModel ||\n !registration.instanceContainer ||\n processedContainerUrls.has(registration.instanceContainer)\n ) {\n return null;\n }\n\n processedContainerUrls.add(registration.instanceContainer);\n\n return { registration, registeredModel };\n })\n .filter((match) => !!match);\n\n // Removed nested registrations.\n const containerUrls = registrations.map(({ registration }) => registration.instanceContainer);\n\n return registrations.filter(({ registration }) => {\n return !containerUrls.some(\n (containerUrl) =>\n containerUrl &&\n containerUrl !== registration.instanceContainer &&\n registration.instanceContainer?.startsWith(containerUrl),\n );\n });\n }\n\n private async updateTypeRegistrations(remoteModel: SolidModel): Promise<void> {\n if (!isRegisteredModel(remoteModel)) {\n return;\n }\n\n const container = isContainer(remoteModel) ? remoteModel : createRemoteContainer(remoteModel, this.localModels);\n const registeredChildren = isContainer(remoteModel)\n ? getContainerRegisteredClasses(remoteModel.static())\n : [remoteModel.static()];\n\n if (registeredChildren.length === 0) {\n return;\n }\n\n const typeIndex = await this.loadTypeIndex({ create: true });\n\n if (\n typeIndex.registrations.some(\n (registration) =>\n registration.instanceContainer && remoteModel.url.startsWith(registration.instanceContainer),\n )\n ) {\n return;\n }\n\n await container.register(typeIndex, registeredChildren);\n }\n\n private async loadChildren(model: SolidModel, childStatus?: JobStatus): Promise<void> {\n this.assertNotCancelled();\n\n if (!isContainer(model)) {\n return;\n }\n\n const children = await this.loadContainedModels(model, {\n status: childStatus,\n updateProgress: (update) => this.updateProgress(update),\n onDocumentError: (error) => this.handleDocumentError(error),\n onDocumentRead: (document) => {\n if (document.url.endsWith('/') || !document.updatedAt || document.url in this.documentsModifiedAt) {\n return;\n }\n\n this.documentsModifiedAt[document.url] = document.updatedAt;\n },\n onDocumentLoaded: async () => {\n this.assertNotCancelled();\n\n await this.updateProgress();\n },\n onDocumentIgnored: async (document) => {\n if (!document.updatedAt) {\n return;\n }\n\n await Cloud.getDocumentsCache().remember(\n requireUrlParentDirectory(document.url),\n document.url,\n document.updatedAt,\n );\n },\n });\n\n for (let index = 0; index < children.length; index++) {\n const child = children[index] as SolidModel;\n\n if (child instanceof Tombstone) {\n this.tombstones.add(child);\n\n continue;\n }\n\n if (this.tombstones.hasKey(child.url)) {\n await this.deleteChild(model, child);\n\n continue;\n }\n\n await this.loadChildren(child, childStatus?.children?.[index]);\n\n if (childStatus?.children?.[index]) {\n await this.updateProgress(() => (required(childStatus.children?.[index]).completed = true));\n }\n }\n }\n\n private async deleteChild(model: SolidModel, child: SolidModel): Promise<void> {\n for (const relation of model.static('relations')) {\n const relationInstance = model.requireRelation(relation);\n\n if (!relationInstance.related) {\n continue;\n }\n\n if (Array.isArray(relationInstance.related)) {\n relationInstance.related = relationInstance.related.filter((relatedModel) => relatedModel !== child);\n\n continue;\n }\n\n if (relationInstance.related === child) {\n relationInstance.related = null;\n\n continue;\n }\n }\n\n await child.forceDelete();\n }\n\n private async saveModelAndRelated(\n model: SolidModel,\n status?: JobStatus,\n processedModels?: Set<SolidModel>,\n ): Promise<void> {\n this.assertNotCancelled();\n processedModels ??= new Set();\n\n if (processedModels.has(model)) {\n return;\n }\n\n processedModels.add(model);\n\n if (isRemoteModel(model) && model.isSoftDeleted()) {\n model.enableHistory();\n model.enableTombstone();\n\n await model.forceDelete();\n\n return;\n }\n\n if (model.getDocumentUrl() && this.documentsWithErrors.has(model.requireDocumentUrl())) {\n return;\n }\n\n const wasDirty = model.isDirty();\n\n await model.save();\n\n if (wasDirty || isRemoteModel(model)) {\n this.syncedModelUrls.add(model.url);\n }\n\n if (isRemoteModel(model)) {\n const documentUrl = model.requireDocumentUrl();\n const modifiedAt = this.documentsModifiedAt[documentUrl];\n\n if (modifiedAt) {\n await Cloud.getDocumentsCache().remember(\n requireUrlParentDirectory(documentUrl),\n documentUrl,\n modifiedAt,\n );\n\n delete this.documentsModifiedAt[documentUrl];\n }\n }\n\n const children = arrayWithout(getRelatedAppModels(model), model);\n const childrenStatuses = status ? children.map(() => ({ completed: false })) : [];\n\n if (status) {\n status.children = childrenStatuses;\n }\n\n for (let index = 0; index < children.length; index++) {\n const child = children[index] as SolidModel;\n const childStatus = childrenStatuses[index];\n\n await this.saveModelAndRelated(child, childStatus, processedModels);\n\n if (childStatus) {\n await this.updateProgress(() => (childStatus.completed = true));\n }\n }\n }\n\n private async synchronizeModels(remoteModels: ObjectsMap<SolidModel>): Promise<SolidModel[]> {\n const synchronizedModelUrls = new Set<string>();\n const deletedModels = new Set<SolidModel>();\n\n for (const remoteModel of remoteModels.items()) {\n if (remoteModel instanceof Tombstone) {\n const localModel = this.localModels.get(remoteModel.resourceUrl);\n\n if (localModel) {\n await localModel.forceDelete();\n\n deletedModels.add(localModel);\n }\n\n continue;\n }\n\n const localModel = getLocalModel(remoteModel, this.localModels);\n\n if (!localModel.exists()) {\n this.syncedModelUrls.add(localModel.url);\n }\n\n await this.loadChildren(localModel);\n await SolidModel.synchronize(localModel, remoteModel, {\n constructors: getCloneConstructors(localModel),\n });\n await this.reconcileInconsistencies(localModel, remoteModel);\n await this.saveModelAndRelated(localModel);\n await this.addLocalModel(localModel);\n\n if (!this.rootLocalModels.includes(localModel)) {\n this.rootLocalModels.push(localModel);\n }\n\n synchronizedModelUrls.add(localModel.url);\n }\n\n for (const localModel of this.rootLocalModels) {\n if (deletedModels.has(localModel) || synchronizedModelUrls.has(localModel.url)) {\n continue;\n }\n\n await this.loadChildren(localModel);\n\n const remoteModel = getRemoteModel(localModel, remoteModels);\n\n await SolidModel.synchronize(localModel, remoteModel, {\n constructors: getCloneConstructors(localModel),\n });\n\n remoteModels.add(remoteModel);\n }\n\n const dirtyRemoteModels = [];\n\n for (const remoteModel of remoteModels.getItems()) {\n if (isDirtyOrHasDirtyChildren(remoteModel)) {\n dirtyRemoteModels.push(remoteModel);\n\n continue;\n }\n\n await this.rememberModelDocuments(remoteModel);\n }\n\n return dirtyRemoteModels;\n }\n\n private async reconcileInconsistencies(\n localModel: SolidModel,\n remoteModel: SolidModel,\n processedModels?: Set<SolidModel>,\n ): Promise<void> {\n localModel.rebuildAttributesFromHistory();\n localModel.setAttributes(remoteModel.getAttributes(true));\n\n processedModels ??= new Set();\n processedModels.add(localModel);\n\n for (const relation of getContainerRelations(localModel.static())) {\n await this.synchronizeContainerDocuments(\n localModel.requireRelation<SolidContainsRelation>(relation),\n remoteModel.requireRelation<SolidContainsRelation>(relation),\n );\n }\n\n const remoteRelatedModels = map(getRelatedAppModels(remoteModel), 'url');\n\n for (const localRelatedModel of getRelatedAppModels(localModel)) {\n if (\n processedModels.has(localRelatedModel) ||\n !localRelatedModel.isRelationLoaded('operations') ||\n !remoteRelatedModels.hasKey(localRelatedModel.url)\n ) {\n continue;\n }\n\n await this.reconcileInconsistencies(\n localRelatedModel,\n remoteRelatedModels.require(localRelatedModel.url),\n processedModels,\n );\n }\n\n if (localModel.isDirty()) {\n await SolidModel.synchronize(localModel, remoteModel, {\n constructors: getCloneConstructors(localModel),\n });\n }\n }\n\n private async synchronizeContainerDocuments(\n localRelation: SolidContainsRelation,\n remoteRelation: SolidContainsRelation,\n ): Promise<void> {\n const localModels = map(localRelation.related ?? [], 'url');\n const remoteModels = map(remoteRelation.related ?? [], 'url');\n const newLocalModelUrls = localModels\n .getKeys()\n .filter((url) => !remoteModels.hasKey(url) && !remoteModels.hasKey(encodeURI(url)));\n const newRemoteModelUrls = remoteModels\n .getKeys()\n .filter((url) => !localModels.hasKey(url) && !localModels.hasKey(encodeURI(url)));\n\n for (const url of newLocalModelUrls) {\n const localModel = localModels.require(url);\n const remoteModel = cloneLocalModel(localModel);\n\n remoteRelation.addRelated(remoteModel);\n remoteModels.add(remoteModel);\n }\n\n for (const url of newRemoteModelUrls) {\n const remoteModel = remoteModels.require(url);\n const localModel = cloneRemoteModel(remoteModel);\n\n localRelation.addRelated(localModel);\n localModels.add(localModel);\n this.syncedModelUrls.add(localModel.url);\n }\n\n for (const localModel of localModels.items()) {\n const remoteModel = remoteModels.require(localModel.url);\n\n await SolidModel.synchronize(localModel, remoteModel, {\n constructors: getCloneConstructors(localModel),\n });\n await this.saveModelAndRelated(localModel);\n }\n }\n\n private async rememberModelDocuments(model: SolidModel): Promise<void> {\n this.syncedModelUrls.add(model.url);\n\n if (!isContainer(model)) {\n const documentUrl = model.requireDocumentUrl();\n const modifiedAt = this.documentsModifiedAt[documentUrl];\n\n if (modifiedAt) {\n await Cloud.getDocumentsCache().remember(\n requireUrlParentDirectory(documentUrl),\n documentUrl,\n modifiedAt,\n );\n\n delete this.documentsModifiedAt[documentUrl];\n }\n\n return;\n }\n\n const children = getContainerRelations(model.static())\n .map((relation) => model.getRelationModels(relation) ?? [])\n .flat();\n\n for (const child of children) {\n await this.rememberModelDocuments(child);\n }\n }\n\n private async ignoringDocumentErrors(operation: Function): Promise<void> {\n try {\n await operation();\n } catch (error) {\n this.handleDocumentError(error);\n }\n }\n\n private handleDocumentError(error: unknown): void {\n if (isInstanceOf(error, MalformedSolidDocumentError)) {\n // eslint-disable-next-line no-console\n console.warn(error.message);\n\n error.documentUrl && this.documentsWithErrors.add(error.documentUrl);\n\n return;\n }\n\n if (isInstanceOf(error, InvalidModelAttributes)) {\n // eslint-disable-next-line no-console\n console.warn(error.message);\n\n const primaryKey = error.attributes[requireBootedModel(error.modelName).primaryKey];\n const documentUrl = primaryKey && urlRoute(toString(primaryKey));\n\n documentUrl && this.documentsWithErrors.add(documentUrl);\n\n return;\n }\n\n throw error;\n }\n\n}\n","import { defineServiceState, replaceExisting, translateWithDefault } from '@aerogel/core';\nimport { Solid } from '@aerogel/plugin-solid';\nimport type { ErrorSource } from '@aerogel/core';\nimport type { Nullable } from '@noeldemartin/utils';\nimport type { SolidModelConstructor, SolidSchemaDefinition } from 'soukai-solid';\n\nimport Migrate from '@aerogel/plugin-local-first/jobs/Migrate';\nimport type Sync from '@aerogel/plugin-local-first/jobs/Sync';\n\nexport const CloudStatus = {\n Disconnected: 'disconnected',\n Offline: 'offline',\n Online: 'online',\n Syncing: 'syncing',\n Migrating: 'migrating',\n} as const;\n\nexport interface ModelRegistration {\n modelClass: SolidModelConstructor;\n path?: string;\n}\n\nexport type TCloudStatus = (typeof CloudStatus)[keyof typeof CloudStatus];\n\nexport const DEFAULT_STATE = { manualSetup: false };\n\nexport default defineServiceState({\n name: 'cloud',\n persist: [\n 'localModelUpdates',\n 'migrationDismissed',\n 'migrationJob',\n 'modelCollections',\n 'rootModelCollections',\n 'pollingEnabled',\n 'pollingMinutes',\n 'ready',\n 'startupSync',\n ],\n initialState: () => ({\n autoPush: true,\n localModelUpdates: {} as Record<string, number>,\n migrationDismissed: false,\n migrationJob: null as Nullable<Migrate>,\n migrationPostponed: false,\n modelCollections: {} as Record<string, string[]>,\n rootModelCollections: {} as Record<string, string>,\n pollingEnabled: true,\n pollingMinutes: 10,\n ready: false,\n manualSetup: DEFAULT_STATE.manualSetup,\n registeredModels: [] as ModelRegistration[],\n schemaMigrations: new Map<SolidModelConstructor, SolidModelConstructor | SolidSchemaDefinition>(),\n setupDismissed: false,\n setupOngoing: false,\n startupSync: true,\n status: CloudStatus.Disconnected as TCloudStatus,\n syncError: null as Nullable<ErrorSource>,\n syncJob: null as Nullable<Sync>,\n }),\n serialize: (state) => replaceExisting(state, { migrationJob: state.migrationJob?.serialize() }),\n restore: (state) =>\n replaceExisting(state, {\n migrationJob: state.migrationJob && Migrate.restore(state.migrationJob),\n }),\n watch: {\n migrationJob(migrationJob) {\n migrationJob?.listeners.add({ onUpdated: () => this.updatePersistedState('migrationJob') });\n },\n },\n computed: {\n disconnected: ({ status }) => status === CloudStatus.Disconnected,\n online: ({ status }) => status === CloudStatus.Online,\n offline: ({ status }) => status === CloudStatus.Offline,\n syncing: ({ status }) => status === CloudStatus.Syncing,\n migrating: ({ status }) => status === CloudStatus.Migrating,\n localChanges({ localModelUpdates }) {\n return Object.values(localModelUpdates).reduce((total, count) => total + count, 0);\n },\n dirty(): boolean {\n return this.localChanges > 0;\n },\n migrationStarted({ migrationJob }): boolean {\n return !!migrationJob;\n },\n migrationDisabledReason({ status, ready }): string | null {\n if (!Solid.isLoggedIn()) {\n return translateWithDefault(\n 'cloud.migrationNotLoggedIn',\n 'You need to reconnect before starting the migration',\n );\n }\n\n if (!ready) {\n return translateWithDefault(\n 'cloud.migrationNotReady',\n 'You need to backup your data before starting the migration',\n );\n }\n\n if (status === CloudStatus.Syncing || status === CloudStatus.Migrating) {\n return translateWithDefault(\n 'cloud.migrationNotSyncing',\n 'Wait for syncing to finish before starting the migration',\n );\n }\n\n if (!this.online) {\n return translateWithDefault(\n 'cloud.migrationNotOnline',\n 'You need to be online in order to start the migration',\n );\n }\n\n return null;\n },\n },\n});\n","import {\n Semaphore,\n after,\n facade,\n fail,\n getLocationQueryParameter,\n hasLocationQueryParameter,\n isArray,\n isTesting,\n parseBoolean,\n} from '@noeldemartin/utils';\nimport { Errors, Events, appNamespace, dispatch, translateWithDefault } from '@aerogel/core';\nimport { Solid } from '@aerogel/plugin-solid';\nimport {\n DocumentsCache,\n SolidContainer,\n SolidModel,\n Tombstone,\n isContainer,\n isContainerClass,\n isSolidModel,\n} from 'soukai-solid';\nimport { getTrackedModels, trackModels, trackModelsCollection } from '@aerogel/plugin-soukai';\nimport { watchEffect } from 'vue';\nimport { getBootedModels, requireEngine } from 'soukai';\nimport type { Authenticator } from '@aerogel/plugin-solid';\nimport type { Engine } from 'soukai';\nimport type { JobListener } from '@aerogel/core';\nimport type { SolidContainsRelation, SolidModelConstructor, SolidSchemaDefinition } from 'soukai-solid';\n\nimport {\n clearLocalModelUpdates,\n createRemoteModel,\n getLocalModels,\n getRemoteClass,\n getRemoteContainersCollection,\n updateRemoteModel,\n} from '@aerogel/plugin-local-first/lib/mirroring';\nimport Backup from '@aerogel/plugin-local-first/jobs/Backup';\nimport Migrate from '@aerogel/plugin-local-first/jobs/Migrate';\nimport Sync from '@aerogel/plugin-local-first/jobs/Sync';\nimport SyncQueue from '@aerogel/plugin-local-first/lib/SyncQueue';\nimport {\n getContainedModels,\n getContainerRelations,\n getRelatedClasses,\n} from '@aerogel/plugin-local-first/lib/inference';\n\nimport Service, { CloudStatus } from './Cloud.state';\n\nexport interface RegisterOptions {\n path?: string;\n}\n\nexport interface SyncOptions extends JobListener {\n model?: SolidModel;\n models?: SolidModel[];\n refreshUserProfile?: boolean;\n syncDirty?: boolean;\n}\n\nexport class CloudService extends Service {\n\n protected asyncLock: Semaphore = new Semaphore();\n protected engine: Engine | null = null;\n protected pollingInterval: ReturnType<typeof setInterval> | null = null;\n protected documentsCache: DocumentsCache | null = null;\n\n public async whenReady<T>(callback: () => T): Promise<T> {\n if (this.ready) {\n return callback();\n }\n\n return new Promise((resolve) => {\n const onReady = () => resolve(callback());\n\n Events.once('cloud:ready', onReady);\n });\n }\n\n public async setup(modelUrlMappings?: WeakMap<SolidModelConstructor, Record<string, string>>): Promise<void> {\n this.setupOngoing = true;\n\n try {\n await this.backup(modelUrlMappings);\n await this.setReady(true);\n await this.sync();\n } finally {\n this.setupOngoing = false;\n }\n }\n\n public getEngine(): Engine | null {\n return this.engine;\n }\n\n public requireEngine(): Engine {\n return this.engine ?? fail('Could not get required Engine');\n }\n\n public dismissSetup(): void {\n this.setupDismissed = true;\n }\n\n public dismissMigration(): void {\n this.migrationDismissed = true;\n }\n\n public postponeMigration(): void {\n this.migrationPostponed = true;\n }\n\n public async syncIfOnline(options?: SyncOptions): Promise<void>;\n public async syncIfOnline(model: SolidModel): Promise<void>;\n public async syncIfOnline(models: SolidModel[]): Promise<void>;\n public async syncIfOnline(config: SyncOptions | SolidModel | SolidModel[] = {}): Promise<void> {\n if (!this.online) {\n return;\n }\n\n await this.sync(config as SyncOptions);\n }\n\n public async sync(options?: SyncOptions): Promise<void>;\n public async sync(model: SolidModel): Promise<void>;\n public async sync(models: SolidModel[]): Promise<void>;\n public async sync(config: SyncOptions | SolidModel | SolidModel[] = {}): Promise<void> {\n const options = isArray(config)\n ? { models: config }\n : config instanceof SolidModel\n ? { model: config }\n : config;\n\n if (!Solid.isLoggedIn() || !this.ready || !this.online) {\n return;\n }\n\n await this.asyncLock.run(async () => {\n let models = options.model ? [options.model] : options.models;\n const start = Date.now();\n\n this.syncError = null;\n this.status = CloudStatus.Syncing;\n\n SyncQueue.clear(models);\n\n try {\n await Events.emit('cloud:sync-started', models);\n\n if (options.refreshUserProfile) {\n await Solid.refreshUserProfile();\n }\n\n const syncDirty = options.syncDirty ?? true;\n let syncs = 0;\n\n do {\n this.syncJob = new Sync(models);\n\n this.syncJob.listeners.add(options);\n\n await dispatch(this.syncJob);\n\n if (this.syncJob.cancelled) {\n return;\n }\n\n syncs++;\n models = this.getDirtyLocalModels().filter(\n (model) => !this.syncJob?.documentsWithErrors.has(model.requireDocumentUrl()),\n );\n } while (syncDirty && models.length > 0 && syncs < 3);\n\n if (!isTesting('unit')) {\n await after({ milliseconds: Math.max(500, 1000 - (Date.now() - start)) });\n }\n\n this.syncJob = null;\n } catch (error) {\n if (isTesting()) {\n throw error;\n }\n\n this.syncJob = null;\n this.syncError = error;\n\n await Errors.report(error, translateWithDefault('cloud.syncFailed', 'Sync failed'));\n } finally {\n this.status = CloudStatus.Online;\n\n await Events.emit('cloud:sync-completed', models);\n }\n });\n }\n\n public shouldMigrate(): boolean {\n return this.schemaMigrations.size > 0;\n }\n\n public async migrate(listener?: JobListener): Promise<void> {\n if (!this.online || !Solid.isLoggedIn() || !this.ready) {\n throw new Error('Data cannot be migrated at the moment');\n }\n\n if (!this.shouldMigrate()) {\n return;\n }\n\n await this.asyncLock.run(async () => {\n this.status = CloudStatus.Migrating;\n this.migrationJob ??= new Migrate();\n\n const start = Date.now();\n const removeListeners: Function[] = [];\n const models = (this.migrationJob.models ??= getLocalModels());\n\n SyncQueue.clear(models);\n\n try {\n listener && removeListeners.push(this.migrationJob.listeners.add(listener));\n\n await Events.emit('cloud:migration-started', models);\n await dispatch(this.migrationJob);\n\n if (this.migrationJob.cancelled) {\n await Events.emit('cloud:migration-cancelled', models);\n\n return;\n }\n\n this.migrationJob = null;\n this.migrationDismissed = false;\n this.migrationPostponed = false;\n\n await after({ milliseconds: Math.max(0, 1000 - (Date.now() - start)) });\n await Events.emit('cloud:migration-completed', models);\n } catch (error) {\n await Errors.report(error, translateWithDefault('cloud.migrationFailed', 'Migration failed'));\n } finally {\n this.status = CloudStatus.Online;\n\n removeListeners.forEach((removeListener) => removeListener?.());\n }\n });\n }\n\n public async register(modelClass: SolidModelConstructor, options: RegisterOptions = {}): Promise<void> {\n if (this.registeredModels.find((registered) => modelClass === registered.modelClass)) {\n return;\n }\n\n const engine = this.engine;\n\n if (engine) {\n getRelatedClasses(modelClass).forEach((relatedClass) => getRemoteClass(relatedClass).setEngine(engine));\n }\n\n this.whenReady(async () => {\n const rootCollection = this.rootModelCollections[modelClass.modelName];\n\n modelClass.useSoftDeletes(true);\n\n await modelClass.exclusive(\n async () =>\n (modelClass.collection = rootCollection ?? getRemoteContainersCollection(modelClass, options.path)),\n );\n });\n\n await trackModels(modelClass, {\n created: (model) => this.ready && createRemoteModel(model),\n updated: (model) => this.ready && updateRemoteModel(model),\n deleted: (model) =>\n this.ready && clearLocalModelUpdates(new Set([model.url ?? model.getDeletedPrimaryKey()])),\n });\n\n if (isContainerClass(modelClass)) {\n getContainerRelations(modelClass).forEach((relation) => {\n const relatedClass = modelClass\n .instance()\n .requireRelation<SolidContainsRelation>(relation).relatedClass;\n\n relatedClass.on('created', (model) => this.ready && createRemoteModel(model));\n relatedClass.on('updated', (model) => this.ready && updateRemoteModel(model));\n relatedClass.on(\n 'deleted',\n (model) =>\n this.ready && clearLocalModelUpdates(new Set([model.url ?? model.getDeletedPrimaryKey()])),\n );\n });\n }\n\n this.registeredModels.push({ modelClass, path: options.path });\n\n for (const collection of this.modelCollections[modelClass.modelName] ?? []) {\n await trackModelsCollection(modelClass, collection);\n }\n }\n\n public registerSchemaMigration(\n modelClass: SolidModelConstructor,\n schema: SolidModelConstructor | SolidSchemaDefinition,\n ): void {\n this.schemaMigrations.set(modelClass, schema);\n }\n\n public requireRemoteCollection(modelClass: SolidModelConstructor): string {\n for (const registration of this.registeredModels) {\n if (modelClass !== registration.modelClass) {\n continue;\n }\n\n return getRemoteContainersCollection(registration.modelClass, registration.path);\n }\n\n throw new Error(`Failed resolving remote collection for '${modelClass.modelName}' model`);\n }\n\n public getDocumentsCache(): DocumentsCache {\n if (!this.documentsCache) {\n this.documentsCache = new DocumentsCache(appNamespace(), requireEngine());\n }\n\n return this.documentsCache;\n }\n\n protected override async boot(): Promise<void> {\n await Solid.booted;\n\n Solid.isLoggedIn() && this.login(Solid.authenticator);\n\n Events.on('auth:login', ({ authenticator }) => this.login(authenticator));\n Events.on('auth:logout', () => this.logout());\n Events.on('purge-storage', () => this.getDocumentsCache().clear());\n Events.once('application-ready', () => this.onApplicationReady());\n Events.once('application-mounted', () => this.onApplicationMounted());\n\n watchEffect(() => {\n this.pollingInterval && clearInterval(this.pollingInterval);\n\n if (!this.pollingEnabled || this.migrationJob) {\n this.pollingInterval = null;\n\n return;\n }\n\n this.pollingInterval = setInterval(() => this.sync(), this.pollingMinutes * 60 * 1000);\n });\n\n this.watchNetworkStatus();\n await this.bustDocumentsCache();\n await this.registerModels();\n }\n\n protected getDirtyLocalModels(): SolidModel[] {\n const urls = Object.keys(this.localModelUpdates);\n const dirtyLocalModels = [];\n\n for (const { modelClass } of this.registeredModels) {\n for (const model of getTrackedModels(modelClass, { includeSoftDeleted: true })) {\n dirtyLocalModels.push(...this.getModelsIn(urls, model));\n }\n }\n\n return dirtyLocalModels;\n }\n\n protected getModelsIn(urls: string[], model: SolidModel): SolidModel[] {\n const models = [];\n\n if (urls.includes(model.url)) {\n models.push(model);\n }\n\n if (isContainer(model)) {\n models.push(\n ...getContainedModels(model)\n .map((containedModel) => this.getModelsIn(urls, containedModel))\n .flat(),\n );\n }\n\n return models;\n }\n\n protected async setReady(ready: boolean): Promise<void> {\n if (this.ready || !ready) {\n return;\n }\n\n await Events.emit('cloud:ready');\n\n this.ready = true;\n }\n\n protected async backup(modelUrlMappings?: WeakMap<SolidModelConstructor, Record<string, string>>): Promise<void> {\n await Events.emit('cloud:backup-started');\n\n modelUrlMappings ??= new WeakMap();\n\n const job = new Backup();\n\n for (const { modelClass, path } of this.registeredModels) {\n for (const [local, remote] of Object.entries(modelUrlMappings.get(modelClass) ?? {})) {\n job.migrateUrl(modelClass, local, remote);\n }\n\n const localCollection = modelClass.instance().getDefaultCollection();\n const remoteCollection = getRemoteContainersCollection(modelClass, path);\n\n await modelClass.exclusive(async () => (modelClass.collection = remoteCollection));\n\n job.migrateCollection(modelClass, localCollection, remoteCollection);\n }\n\n await dispatch(job);\n await Events.emit('cloud:backup-completed');\n }\n\n protected async onApplicationReady(): Promise<void> {\n if (this.ready || !Solid.isLoggedIn()) {\n return;\n }\n\n await this.setReady(!getLocalModels().some((model) => model.url.startsWith('solid://')));\n }\n\n protected async onApplicationMounted(): Promise<void> {\n if (Solid.isLoggedIn() && !this.ready && !this.manualSetup) {\n await this.setup();\n\n return;\n }\n\n if (!this.syncOnStartup()) {\n return;\n }\n\n await this.sync();\n }\n\n protected login(authenticator: Authenticator): void {\n const relatedClasses = [...this.registeredModels]\n .map(({ modelClass }) => getRelatedClasses(modelClass))\n .flat()\n .concat([Tombstone]);\n\n this.status = CloudStatus.Online;\n this.engine = authenticator.engine;\n\n getRemoteClass(SolidContainer).setEngine(this.engine);\n\n for (const relatedClass of relatedClasses) {\n getRemoteClass(relatedClass).setEngine(this.engine);\n }\n }\n\n protected async logout(): Promise<void> {\n this.setState({\n autoPush: true,\n localModelUpdates: {},\n migrationDismissed: false,\n migrationJob: null,\n migrationPostponed: false,\n modelCollections: {},\n rootModelCollections: {},\n pollingEnabled: true,\n pollingMinutes: 10,\n ready: false,\n schemaMigrations: new Map(),\n setupDismissed: false,\n setupOngoing: false,\n startupSync: true,\n status: CloudStatus.Disconnected,\n syncError: null,\n syncJob: null,\n });\n\n await this.getDocumentsCache().clear();\n }\n\n private watchNetworkStatus(): void {\n globalThis.addEventListener('online', () => {\n if (this.status !== CloudStatus.Offline) {\n return;\n }\n\n this.status = CloudStatus.Online;\n });\n\n globalThis.addEventListener('offline', () => {\n if (this.status !== CloudStatus.Online) {\n return;\n }\n\n this.status = CloudStatus.Offline;\n });\n }\n\n private syncOnStartup(): boolean {\n if (hasLocationQueryParameter('startupSync')) {\n return parseBoolean(getLocationQueryParameter('startupSync'));\n }\n\n if (this.migrationJob) {\n return false;\n }\n\n return this.startupSync;\n }\n\n private async bustDocumentsCache(): Promise<void> {\n if (\n !hasLocationQueryParameter('bustDocumentsCache') ||\n !parseBoolean(getLocationQueryParameter('bustDocumentsCache'))\n ) {\n return;\n }\n\n await this.getDocumentsCache().clear();\n }\n\n private async registerModels(): Promise<void> {\n const models = getBootedModels();\n\n for (const model of models.values()) {\n if (!isSolidModel(model) || !model.cloud) {\n continue;\n }\n\n await this.register(model, typeof model.cloud === 'boolean' ? {} : model.cloud);\n }\n }\n\n}\n\nexport default facade(CloudService);\n\ndeclare module '@aerogel/core' {\n export interface EventsPayload {\n 'cloud:ready': void;\n 'cloud:backup-started': void;\n 'cloud:backup-completed': void;\n 'cloud:migration-started': SolidModel[];\n 'cloud:migration-cancelled': SolidModel[];\n 'cloud:migration-completed': SolidModel[];\n 'cloud:sync-started': SolidModel[] | undefined;\n 'cloud:sync-completed': SolidModel[] | undefined;\n }\n}\n\ndeclare module 'soukai-solid' {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n namespace SolidModel {\n export const cloud: boolean | RegisterOptions | undefined;\n }\n}\n","<template>\n <Modal :title=\"$td('cloud.logIn.title', 'Connect account')\">\n <Markdown\n lang-key=\"cloud.logIn.info\"\n lang-default=\"Log in to your [Solid account](https://solidproject.org) to keep data safe across devices.\"\n />\n <Link\n class=\"text-sm\"\n @click=\"\n $ui.alert(\n $td('cloud.logIn.learnMore', 'What is Solid?'),\n $td(\n 'cloud.logIn.learnMoreMessage',\n 'Solid is a decentralized storage protocol built on top of web standards. ' +\n 'If you want to use this app across devices, ' +\n 'you can use Solid to keep changes in sync. ' +\n 'Even if you use it in a single device, ' +\n 'this will also keep your data secure in case your device is lost.\\n\\n' +\n 'In any case, Focus works 100% offline and you can connect your Solid POD later on. ' +\n 'If you\\'ve never heard of Solid and you\\'re just trying things out, ' +\n 'you can keep using it without an account.\\n\\n' +\n '[Learn more](https://solidproject.org)'\n )\n )\n \"\n >\n {{ $td('cloud.logIn.learnMore', 'What is Solid?') }}\n </Link>\n <SolidLogin no-loading class=\"mt-4\" />\n </Modal>\n</template>\n\n<script setup lang=\"ts\">\nimport { Link, Markdown, Modal } from '@aerogel/core';\nimport { SolidLogin } from '@aerogel/plugin-solid';\n</script>\n","<template>\n <details v-if=\"!$solid.hasLoggedIn()\" class=\"mt-4\">\n <summary>\n <span class=\"text-base font-semibold\">{{ $td('settings.dangerZone', 'Danger zone') }}</span>\n </summary>\n <Button variant=\"danger\" class=\"mt-4\" @click=\"purgeData()\">\n <IconTrash class=\"size-4\" />\n <span class=\"ml-1\">{{ $td('settings.purge', 'Purge data') }}</span>\n </Button>\n </details>\n</template>\n\n<script setup lang=\"ts\">\nimport IconTrash from '~icons/zondicons/trash';\n\nimport { Button, Storage, UI, translateWithDefault } from '@aerogel/core';\n\nimport AccountLoginModal from '@aerogel/plugin-local-first/components/AccountLoginModal.vue';\n\nasync function purgeData(): Promise<void> {\n const confirmed = await UI.confirm(\n translateWithDefault('settings.purgeConfirmTitle', 'Delete everything?'),\n translateWithDefault(\n 'settings.purgeConfirmMessage',\n 'If you proceed, all your data will be deleted forever. ' +\n 'If you want to save it before wiping this device, ' +\n 'you can [connect to your Solid account](#action:connect) first.',\n ),\n {\n acceptVariant: 'danger',\n acceptText: translateWithDefault('settings.purgeConfirmAccept', 'Purge data'),\n actions: { connect: () => UI.modal(AccountLoginModal) },\n },\n );\n\n if (!confirmed) {\n return;\n }\n\n await UI.closeAllModals();\n await Storage.purge();\n}\n</script>\n","import { defineSettings } from '@aerogel/core';\n\nimport PurgeData from './PurgeData.vue';\n\nexport default defineSettings([\n {\n priority: 0,\n component: PurgeData,\n },\n]);\n","<template>\n <Modal title-hidden close-hidden :title=\"$td('account.title', 'Account')\">\n <div class=\"relative flex items-center rounded-md bg-gray-100 p-4 pr-12\">\n <SolidAvatar class=\"mr-2 size-16 shrink-0\" />\n <div class=\"flex flex-col overflow-hidden\">\n <span class=\"font-semibold\">{{ $solid.user?.name ?? $td('user.anonymous', 'Anonymous') }}</span>\n <Link :href=\"$solid.user?.webId\" class=\"mt-0.5 truncate text-sm font-light text-gray-500\">\n {{ $solid.user?.webId }}\n </Link>\n </div>\n <Button\n size=\"icon\"\n variant=\"ghost\"\n class=\"absolute top-1 right-1 hover:bg-gray-200\"\n :aria-label=\"$td('user.settings', 'Settings')\"\n :title=\"$td('user.settings', 'Settings')\"\n @click=\"$ui.modal(SettingsModal)\"\n >\n <IconCog class=\"size-5\" />\n </Button>\n </div>\n\n <div class=\"px-2\">\n <div v-if=\"$cloud.syncing\" class=\"mt-4 flex items-center gap-2\">\n <IconRefresh class=\"mt-0.5 size-6 shrink-0 animate-spin self-start text-green-500\" />\n <div class=\"flex w-full flex-col\">\n <Markdown lang-key=\"cloud.info.syncing\" lang-default=\"Synchronizing...\" />\n <ProgressBar v-if=\"$cloud.syncJob\" :job=\"$cloud.syncJob\" filled-class=\"bg-green-500\" />\n </div>\n </div>\n <div v-else-if=\"$solid.loginOngoing\" class=\"mt-4 flex items-center gap-2\">\n <IconRefresh class=\"mt-0.5 size-6 shrink-0 animate-spin self-start text-green-500\" />\n <Markdown lang-key=\"cloud.info.reconnecting\" lang-default=\"Reconnecting...\" />\n </div>\n <div v-else-if=\"error\" class=\"mt-4 flex items-center gap-2\">\n <IconWarning class=\"mt-0.5 size-6 shrink-0 self-start text-red-500\" />\n <div>\n <Markdown :text=\"errorDescription\" />\n <Link\n v-if=\"showErrorDetails\"\n class=\"text-sm text-red-700 opacity-50 hover:opacity-75 focus-visible:opacity-75\"\n @click=\"$errors.inspect(error)\"\n >\n {{ $td('errors.viewDetails', 'View details') }}\n </Link>\n </div>\n </div>\n <div v-else-if=\"!$cloud.ready\" class=\"mt-4 flex items-center gap-2\">\n <IconWarning class=\"mt-0.5 size-6 shrink-0 self-start text-yellow-500\" />\n <Markdown lang-key=\"cloud.info.setup\" lang-default=\"Your data is not backed up yet.\" />\n </div>\n <div v-else-if=\"$cloud.dirty\" class=\"mt-4 flex items-center gap-2\">\n <IconWarning class=\"mt-0.5 size-6 shrink-0 self-start text-yellow-500\" />\n <Markdown\n lang-key=\"cloud.info.changes\"\n lang-default=\"Everything is up to date. | There is one local change. | There are {n} local changes.\"\n :lang-params=\"$cloud.localChanges\"\n />\n </div>\n <div v-else-if=\"$cloud.online || $cloud.offline\" class=\"mt-4 flex items-center gap-2\">\n <IconCheckmarkOutline\n class=\"mt-0.5 size-6 shrink-0 self-start\"\n :class=\"{ 'text-green-500': $cloud.online, 'text-gray-700': $cloud.offline }\"\n />\n <Markdown\n v-if=\"$cloud.online\"\n lang-key=\"cloud.info.changes\"\n lang-default=\"Everything is up to date.\"\n :lang-params=\"0\"\n />\n <Markdown\n v-else\n lang-key=\"cloud.info.offline\"\n lang-default=\"Everything is up to date, but you're currently offline.\"\n />\n </div>\n <div v-else class=\"mt-4 flex items-center gap-2\">\n <IconWarning class=\"mt-0.5 size-6 shrink-0 self-start text-yellow-500\" />\n <Markdown\n lang-key=\"cloud.info.disconnected\"\n lang-default=\"You are disconnected from your Solid account, all the changes you make will remain in your device.\"\n />\n </div>\n <AdvancedOptions class=\"mt-2\">\n <ul class=\"flex flex-col gap-2\">\n <li>\n <Checkbox\n v-model=\"$solid.autoReconnect\"\n label-class=\"text-base\"\n :label=\"$td('cloud.advanced.reconnect', 'Reconnect on startup')\"\n />\n </li>\n <li>\n <Checkbox\n v-model=\"$cloud.startupSync\"\n label-class=\"text-base\"\n :label=\"$td('cloud.advanced.startupSync', 'Synchronize on startup')\"\n />\n </li>\n <li>\n <Checkbox v-model=\"$cloud.pollingEnabled\" label-class=\"text-base\">\n <div class=\"flex items-center\">\n <span aria-hidden=\"true\">{{ pollingText[0] }}</span>\n <EditableContent\n type=\"number\"\n :text=\"`${$cloud.pollingMinutes}`\"\n :aria-label=\"\n $td('cloud.advanced.pollingMinutes', 'Synchronization interval (in minutes)')\n \"\n class=\"focus-within:border-primary-600 mx-1 -mb-px border-b\"\n @update=\"$cloud.pollingMinutes = $event as number\"\n >\n {{ $cloud.pollingMinutes }}\n </EditableContent>\n <span v-if=\"pollingText.length > 1\" aria-hidden=\"true\">{{ pollingText[1] }}</span>\n </div>\n </Checkbox>\n </li>\n </ul>\n </AdvancedOptions>\n </div>\n\n <div v-if=\"!$solid.loginOngoing\" class=\"mt-4 flex flex-row-reverse justify-start gap-2\">\n <Button\n v-if=\"$cloud.syncing\"\n variant=\"secondary\"\n :disabled=\"cancellingSync\"\n @click=\"cancelSync()\"\n >\n <IconStop class=\"size-5\" />\n <span>{{\n cancellingSync ? $td('cloud.stopping', 'Stopping...') : $td('cloud.stop', 'Stop synchronization')\n }}</span>\n </Button>\n <Button v-else-if=\"!$solid.isLoggedIn()\" @click=\"$solid.reconnect({ force: true })\">\n <IconRefresh class=\"size-5\" />\n <span>{{ $td('cloud.reconnect', 'Reconnect') }}</span>\n </Button>\n <Button\n v-else-if=\"$cloud.ready\"\n :disabled=\"$cloud.offline\"\n @click=\"$cloud.sync({ refreshUserProfile: true })\"\n >\n <IconRefresh class=\"size-5\" />\n <span>{{ $td('cloud.sync', 'Synchronize') }}</span>\n </Button>\n <Button v-else @click=\"(($cloud.setupDismissed = false), close(), $cloud.manualSetup || $cloud.setup())\">\n <IconCloudUpload class=\"size-5\" />\n <span>{{ $td('cloud.setup.submit', 'Back up now') }}</span>\n </Button>\n <Button v-if=\"!$cloud.syncing\" variant=\"secondary\" @click=\"$solid.logout()\">\n <IconLogout class=\"size-5\" />\n <span>{{ $cloud.ready ? $td('cloud.logOut', 'Log out') : $td('cloud.disconnect', 'Disconnect') }}</span>\n </Button>\n </div>\n </Modal>\n</template>\n\n<script setup lang=\"ts\">\nimport IconCheckmarkOutline from '~icons/zondicons/checkmark-outline';\nimport IconCloudUpload from '~icons/ic/sharp-cloud-upload';\nimport IconCog from '~icons/zondicons/cog';\nimport IconLogout from '~icons/material-symbols/logout-rounded';\nimport IconRefresh from '~icons/zondicons/refresh';\nimport IconStop from '~icons/ic/baseline-stop';\nimport IconWarning from '~icons/ion/warning';\n\nimport {\n AdvancedOptions,\n Button,\n Checkbox,\n EditableContent,\n Link,\n Markdown,\n Modal,\n ProgressBar,\n SettingsModal,\n translateWithDefault,\n useEvent,\n useModal,\n} from '@aerogel/core';\nimport { computed, ref } from 'vue';\nimport { Solid, SolidAvatar } from '@aerogel/plugin-solid';\n\nimport Cloud from '@aerogel/plugin-local-first/services/Cloud';\n\nconst { close } = useModal();\nconst cancellingSync = ref(false);\nconst pollingText = translateWithDefault('cloud.advanced.polling', 'Synchronize every {minutes} minutes', {\n minutes: '%%separator%%',\n}).split('%%separator%%');\nconst error = computed(() => Solid.error ?? Cloud.syncError);\nconst errorDescription = computed(() => {\n if (!error.value) {\n return;\n }\n\n if (typeof error.value === 'string') {\n return error.value;\n }\n\n return translateWithDefault('cloud.info.error', 'There has been an error connecting.');\n});\nconst showErrorDetails = computed(() => error.value && typeof error.value !== 'string');\n\nasync function cancelSync() {\n if (!Cloud.syncJob) {\n return;\n }\n\n cancellingSync.value = true;\n\n await Promise.race([Cloud.syncJob.cancel(), Cloud.syncJob.completed]);\n\n cancellingSync.value = false;\n}\n\nuseEvent('auth:logout', close);\n</script>\n","<template>\n <div class=\"relative size-12\">\n <button\n class=\"clickable focus-visible:outline-primary-600 flex size-full rounded-full focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2\"\n type=\"button\"\n :aria-label=\"$td('account.open', 'Open account')\"\n :title=\"$td('account.open', 'Open account')\"\n @click=\"$ui.modal(AccountModal)\"\n >\n <SolidAvatar class=\"size-full\" />\n <div\n v-if=\"accountStatus.loading\"\n class=\"absolute -inset-1 animate-spin rounded-full border-2 border-[currentColor_transparent] text-green-500\"\n />\n </button>\n <div\n class=\"pointer-events-none absolute right-0 bottom-0 size-3 rounded-full border-2 border-white\"\n :class=\"accountStatus.classes\"\n >\n <span class=\"sr-only\">{{ accountStatus.message }}</span>\n </div>\n </div>\n</template>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue';\nimport { Solid, SolidAvatar } from '@aerogel/plugin-solid';\nimport { translateWithDefault } from '@aerogel/core';\n\nimport Cloud from '@aerogel/plugin-local-first/services/Cloud';\nimport { CloudStatus } from '@aerogel/plugin-local-first/services/Cloud.state';\n\nimport AccountModal from './AccountModal.vue';\n\ninterface AccountStatus {\n classes: string;\n message: string;\n loading?: boolean;\n}\n\nconst accountStatus = computed((): AccountStatus => {\n if (Cloud.syncing || Solid.loginOngoing) {\n return {\n loading: true,\n classes: 'bg-green-500 sr-only',\n message: getAccountStatusMessage() ?? '',\n };\n }\n\n if (Solid.error || Cloud.syncError) {\n return {\n classes: 'bg-red-500',\n message: translateWithDefault('account.error', 'There has been an error connecting with your account.'),\n };\n }\n\n if (!Solid.isLoggedIn() || Cloud.dirty || !Cloud.ready) {\n return {\n classes: 'bg-yellow-500',\n message: translateWithDefault(\n 'account.dirty',\n 'There are local changes that haven\\'t been synchronized yet.',\n ),\n };\n }\n\n return {\n classes: Cloud.status === CloudStatus.Online ? 'bg-green-500' : 'bg-gray-500',\n message: getAccountStatusMessage() ?? '',\n };\n});\n\nfunction getAccountStatusMessage(): string | undefined {\n switch (Cloud.status) {\n case CloudStatus.Syncing:\n return translateWithDefault('cloud.status.syncing', 'Synchronization in progress');\n case CloudStatus.Migrating:\n return translateWithDefault('cloud.status.migrating', 'Migration in progress');\n case CloudStatus.Online:\n return translateWithDefault('cloud.status.online', 'Online');\n case CloudStatus.Offline:\n return translateWithDefault('cloud.status.offline', 'Offline');\n case CloudStatus.Disconnected:\n return translateWithDefault('cloud.status.disconnected', 'Disconnected');\n }\n}\n</script>\n","<template>\n <DropdownMenu\n align=\"start\"\n :options=\"[\n { label: $td('user.logIn', 'Connect account'), click: () => $ui.modal(AccountLoginModal) },\n { label: $td('user.settings', 'Settings'), click: () => $ui.modal(SettingsModal) },\n ]\"\n >\n <Button\n size=\"icon\"\n variant=\"ghost\"\n :aria-label=\"$td('user.menu', 'Configuration')\"\n :title=\"$td('user.menu', 'Configuration')\"\n >\n <IconCog class=\"size-5\" />\n </Button>\n </DropdownMenu>\n</template>\n\n<script setup lang=\"ts\">\nimport IconCog from '~icons/zondicons/cog';\n\nimport { Button, DropdownMenu, SettingsModal } from '@aerogel/core';\n\nimport AccountLoginModal from './AccountLoginModal.vue';\n</script>\n","<template>\n <AccountLoggedIn v-if=\"$solid.hasLoggedIn()\" />\n <AccountLoggedOut v-else />\n</template>\n\n<script setup lang=\"ts\">\nimport AccountLoggedIn from './AccountLoggedIn.vue';\nimport AccountLoggedOut from './AccountLoggedOut.vue';\n</script>\n","import { App, bootServices } from '@aerogel/core';\nimport type { Plugin } from '@aerogel/core';\n\nimport Cloud from '@aerogel/plugin-local-first/services/Cloud';\nimport { DEFAULT_STATE } from '@aerogel/plugin-local-first/services/Cloud.state';\n\nimport settings from './components/settings';\n\nconst services = { $cloud: Cloud };\n\nexport { Cloud };\nexport * from './components';\nexport * from './services/Cloud';\n\nexport interface Options {\n manualSetup?: boolean;\n}\n\nexport type LocalFirstServices = typeof services;\n\nexport default function localFirst(options: Options = {}): Plugin {\n return {\n name: '@aerogel/local-first',\n async install(app) {\n settings.forEach((setting) => App.addSetting(setting));\n\n if (typeof options.manualSetup === 'boolean') {\n DEFAULT_STATE.manualSetup = options.manualSetup;\n Cloud.manualSetup = options.manualSetup;\n }\n\n await bootServices(app, services);\n },\n };\n}\n\ndeclare module '@aerogel/core' {\n interface Services extends LocalFirstServices {}\n}\n"],"names":["containerRelations","getContainerRegisteredClasses","modelClass","arrayFilter","getContainerRelations","relation","relatedClass","isContainerClass","SolidModel","SolidContainsRelation","getContainedModels","model","models","getRelatedClasses","relatedClasses","instance","getRelatedAppModels","related","isInstanceOf","SolidACLAuthorization","SolidDocument","SolidResource","Metadata","Operation","SolidContainer","isDirtyOrHasDirtyChildren","relationHasDirtyModels","_a","relatedModel","loadAppRelations","onError","builtInRelations","updated","relatedModels","SolidIsContainedByRelation","error","Cloud","required","App","SyncQueue","__publicField","after","operationOrPromise","promise","arrayRemove","children","isContainer","child","SyncQueue$1","facade","remoteClasses","localClasses","cloneConstructors","getRelationClasses","visited","cleanRemoteModelClone","remoteModel","fixRemoteModelClone","operations","operation","PropertyOperation","createRemoteModel","localModel","isRegisteredModelClass","trackModelsCollection","requireUrlParentDirectory","createRemoteContainer","localModels","RemoteContainer","getRemoteClass","path","registeredModelClass","getRemoteContainersCollection","getLocalModel","collection","trackSoukaiModelsCollection","updateRemoteModel","ignoreModelUpdates","modelUpdates","clearLocalModelUpdates","syncedModelUrls","documentsWithErrors","localModelUpdates","syncedModelUrlsArray","url","count","documentUrl","urlRoute","modelUrl","cloneLocalModel","options","constructors","localClass","tap","cloneRemoteModel","getCloneConstructors","completeRemoteModels","remoteModels","RemoteTombstone","Tombstone","remoteModelUrls","missingModelDocumentUrls","tombstones","_b","otherClass","isRemoteModelClass","getLocalClass","a","b","constructor","getLocalModels","getTrackedModels","getSchemaMigrations","clearSchemaMigrations","getSchemaMigration","makeRemoteClass","rootStorage","Solid","containedClass","urlResolveDirectory","getRemoteModel","isRegisteredModel","registeredModel","isRemoteModel","isLocalModel","LocalClass","withLocalHistoryConfig","RemoteClass","attributes","exists","schema","bootModels","remoteClass","fail","Backup","Job","local","remote","engine","requireEngine","collections","droppedCollections","documents","localUrl","document","remoteUrl","solidCollections","filteredCollections","ignoreModelsCollection","localCollection","remoteCollection","key","value","lazy","getter","result","LoadsChildren","container","relationModels","arrayFrom","resourceUrlChunks","arrayChunk","statusChildren","statusChildrenMap","map","updateProgress","resourceUrls","resourceUrl","resource","type","documentChildren","documentTombstones","documentModels","childrenArray","engineDocuments","remoteEngine","_c","readDocument","documentModel","DocumentNotFound","found","relationInstance","typeIndexes","LoadsTypeIndex","user","TracksLocalModels","BaseJob","Migrate","mixed","status","job","childrenStatus","objectMap","modelStatuses","typeIndex","modelStatus","registeredClasses","registration","instanceContainer","migratedModel","migratedOperation","childStatus","isRootStatus","Sync","updateDocumentDate","headers","fallbackDate","date","clearListener","metadata","typedNavigator","Errors","lock","round","remoteModelsArray","localDocuments","index","documentsCache","tombstoneDocuments","tombstone","modifiedAt","pullStatus","registrations","containerModels","containerUrl","update","foundDocuments","childModels","processedContainerUrls","registeredModels","registeredChildren","childrenClass","rdfsClasses","rdfsClass","match","containerUrls","processedModels","wasDirty","arrayWithout","childrenStatuses","synchronizedModelUrls","deletedModels","dirtyRemoteModels","remoteRelatedModels","localRelatedModel","localRelation","remoteRelation","newLocalModelUrls","newRemoteModelUrls","MalformedSolidDocumentError","InvalidModelAttributes","primaryKey","requireBootedModel","toString","CloudStatus","DEFAULT_STATE","Service","defineServiceState","state","replaceExisting","migrationJob","total","ready","translateWithDefault","CloudService","Semaphore","callback","resolve","onReady","Events","modelUrlMappings","config","isArray","start","syncDirty","syncs","dispatch","isTesting","listener","removeListeners","removeListener","registered","rootCollection","trackModels","DocumentsCache","appNamespace","authenticator","watchEffect","urls","dirtyLocalModels","containedModel","hasLocationQueryParameter","parseBoolean","getLocationQueryParameter","getBootedModels","isSolidModel","_createBlock","_unref","Modal","$td","_createVNode","Markdown","Link","_cache","$event","$ui","SolidLogin","purgeData","UI","AccountLoginModal","Storage","$solid","_openBlock","_createElementBlock","_hoisted_1","_createElementVNode","_hoisted_2","_toDisplayString","Button","IconTrash","_hoisted_3","settings","defineSettings","PurgeData","close","useModal","cancellingSync","ref","pollingText","computed","errorDescription","showErrorDetails","cancelSync","useEvent","SolidAvatar","SettingsModal","IconCog","_hoisted_4","$cloud","_hoisted_5","IconRefresh","_hoisted_6","ProgressBar","_hoisted_7","_hoisted_8","IconWarning","$errors","_hoisted_10","_hoisted_11","IconCheckmarkOutline","_normalizeClass","_hoisted_12","_hoisted_9","AdvancedOptions","_hoisted_13","Checkbox","_hoisted_14","_hoisted_15","EditableContent","_hoisted_16","_hoisted_17","IconStop","IconCloudUpload","IconLogout","accountStatus","getAccountStatusMessage","AccountModal","DropdownMenu","AccountLoggedIn","AccountLoggedOut","services","localFirst","app","setting","bootServices"],"mappings":";;;;;;;;;;;AAiBA,MAAMA,yBAA+D,QAAA;AAG9D,SAASC,GAA8BC,GAAgE;AAC1G,SAAOC;AAAA,IACHC,EAAsBF,CAAU,EAAE,IAAI,CAACG,MAAa;AAChD,YAAMC,IAAeJ,EAAW,SAAA,EAAW,gBAAuCG,CAAQ,EAAE;AAE5F,aAAIE,EAAiBD,CAAY,IACtB,KAGJA;AAAA,IACX,CAAC;AAAA,EAAA;AAET;AAEO,SAASF,EAAsBF,GAAyC;AAC3E,SAAKF,GAAmB,IAAIE,CAAU,KAClCF,GAAmB;AAAA,IACfE;AAAA,IACAA,EAAW,UAAU,OAAO,CAACG,MACrBG,EAAW,kBAAkB,SAASH,CAAQ,IACvC,KAGcH,EAAW,SAAA,EAAW,gBAAgBG,CAAQ,aAEpCI,EACtC;AAAA,EAA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0BV,EAAAA,OAAAA,EAAAA,IAAG,iBAAA,UAAA,GAAA,OAAA,MAA4CM,EAAAA,IAAI,MAAMR,EAAAsC,EAAA,CAAa,EAAA;AAAA,MAAA;AAAA;iBAK/M,MAOS;AAAA,QAPTnC,EAOSH,EAAAqB,CAAA,GAAA;AAAA,UANL,MAAK;AAAA,UACL,SAAQ;AAAA,UACP,cAAYnB,EAAAA,IAAG,aAAA,eAAA;AAAA,UACf,OAAOA,EAAAA,IAAG,aAAA,eAAA;AAAA,QAAA;qBAEX,MAA0B;AAAA,YAA1BC,EAA0BH,EAAAuC,EAAA,GAAA,EAAjB,OAAM,UAAQ;AAAA,UAAA;;;;;;;;;;qBCbRzB,EAAAA,OAAO,YAAA,UAA9Bf,EAA+CwE,IAAA,EAAA,KAAA,GAAA,WAC/CxE,EAA2ByE,IAAA,EAAA,KAAA,GAAA;AAAA;ICMzBC,KAAW,EAAE,QAAQ9U,EAAA;AAY3B,SAAwB+U,GAAWzR,IAAmB,IAAY;AAC9D,SAAO;AAAA,IACH,MAAM;AAAA,IACN,MAAM,QAAQ0R,GAAK;AACf,MAAAnD,GAAS,QAAQ,CAACoD,MAAY/U,EAAI,WAAW+U,CAAO,CAAC,GAEjD,OAAO3R,EAAQ,eAAgB,cAC/BqK,GAAc,cAAcrK,EAAQ,aACpCtD,EAAM,cAAcsD,EAAQ,cAGhC,MAAM4R,GAAaF,GAAKF,EAAQ;AAAA,IACpC;AAAA,EAAA;AAER;"}
1
+ {"version":3,"file":"aerogel-plugin-local-first.js","sources":["../src/lib/inference.ts","../src/lib/SyncQueue.ts","../src/lib/mirroring.ts","../src/jobs/Backup.ts","../src/lib/utils.ts","../src/jobs/mixins/LoadsChildren.ts","../src/jobs/mixins/LoadsTypeIndex.ts","../src/jobs/mixins/TracksLocalModels.ts","../src/jobs/Migrate.ts","../src/jobs/Sync.ts","../src/services/Cloud.state.ts","../src/services/Cloud.ts","../src/components/AccountLoginModal.vue","../src/components/settings/PurgeData.vue","../src/components/settings/index.ts","../src/components/AccountModal.vue","../src/components/AccountLoggedIn.vue","../src/components/AccountLoggedOut.vue","../src/components/Account.vue","../src/index.ts"],"sourcesContent":["import {\n Metadata,\n Operation,\n SolidACLAuthorization,\n SolidContainer,\n SolidContainsRelation,\n SolidDocument,\n SolidIsContainedByRelation,\n SolidModel,\n SolidResource,\n isContainerClass,\n isSolidDocumentRelation,\n} from 'soukai-solid';\nimport { arrayFilter, isInstanceOf } from '@noeldemartin/utils';\n\nimport type { SolidContainerConstructor, SolidModelConstructor } from 'soukai-solid';\n\nconst containerRelations: WeakMap<typeof SolidModel, string[]> = new WeakMap();\nconst sameDocumentRelations: WeakMap<typeof SolidModel, string[]> = new WeakMap();\n\nexport function getContainerRegisteredClasses(modelClass: SolidContainerConstructor): SolidModelConstructor[] {\n return arrayFilter(\n getContainerRelations(modelClass).map((relation) => {\n const relatedClass = modelClass.instance().requireRelation<SolidContainsRelation>(relation).relatedClass;\n\n if (isContainerClass(relatedClass)) {\n return false;\n }\n\n return relatedClass;\n }),\n );\n}\n\nexport function getContainerRelations(modelClass: typeof SolidModel): string[] {\n if (!containerRelations.has(modelClass)) {\n containerRelations.set(\n modelClass,\n modelClass.relations.filter((relation) => {\n if (SolidModel.reservedRelations.includes(relation)) {\n return false;\n }\n\n const relationInstance = modelClass.instance().requireRelation(relation);\n\n return relationInstance instanceof SolidContainsRelation;\n }),\n );\n }\n\n return containerRelations.get(modelClass) ?? [];\n}\n\nexport function getContainedModels(model: SolidContainer): SolidModel[] {\n const relations = getContainerRelations(model.static());\n\n return relations.reduce(\n (models, relation) => models.concat(model.getRelationModels(relation) ?? []),\n [] as SolidModel[],\n );\n}\n\nexport function getRelatedClasses(modelClass: SolidModelConstructor): SolidModelConstructor[] {\n const relatedClasses = new Set<SolidModelConstructor>();\n const instance = modelClass.instance();\n\n relatedClasses.add(modelClass);\n\n for (const relation of modelClass.relations) {\n if (modelClass.reservedRelations.includes(relation)) {\n continue;\n }\n\n relatedClasses.add(instance.requireRelation(relation).relatedClass);\n }\n\n return [...relatedClasses.values()];\n}\n\nexport function getRelatedAppModels(model: SolidModel): SolidModel[] {\n return model\n .getRelatedModels()\n .filter(\n (related) =>\n !isInstanceOf(related, SolidACLAuthorization) &&\n !isInstanceOf(related, SolidDocument) &&\n !isInstanceOf(related, SolidResource) &&\n !isInstanceOf(related, Metadata) &&\n !isInstanceOf(related, Operation) &&\n related.static() !== SolidContainer,\n );\n}\n\nexport function getSameDocumentRelations(modelClass: typeof SolidModel): string[] {\n if (!sameDocumentRelations.has(modelClass)) {\n sameDocumentRelations.set(\n modelClass,\n modelClass.relations.filter((relation) => {\n if (SolidModel.reservedRelations.includes(relation)) {\n return false;\n }\n\n const relationInstance = modelClass.instance().requireRelation(relation);\n\n return isSolidDocumentRelation(relationInstance) && relationInstance.useSameDocument;\n }),\n );\n }\n\n return sameDocumentRelations.get(modelClass) ?? [];\n}\n\nexport function isDirtyOrHasDirtyChildren(model: SolidModel): boolean {\n if (model.isDirty()) {\n return true;\n }\n\n if (!(model instanceof SolidContainer)) {\n return false;\n }\n\n const relationHasDirtyModels = (relation: string) => {\n return model.getRelationModels(relation)?.some((relatedModel) => isDirtyOrHasDirtyChildren(relatedModel));\n };\n\n return getContainerRelations(model.static()).some(relationHasDirtyModels);\n}\n\nexport async function loadAppRelations(model: SolidModel, onError?: (error: unknown) => void): Promise<void> {\n const builtInRelations = ['authorizations', 'metadata', 'operations', 'tombstone'];\n\n let updated;\n\n do {\n updated = false;\n\n const relatedModels = getRelatedAppModels(model);\n\n for (const relatedModel of relatedModels) {\n for (const relation of relatedModel.static('relations')) {\n if (\n builtInRelations.includes(relation) ||\n relatedModel.isRelationLoaded(relation) ||\n relatedModel.getRelation(relation) instanceof SolidIsContainedByRelation\n ) {\n continue;\n }\n\n try {\n await relatedModel.loadRelation(relation);\n\n updated = true;\n } catch (error) {\n if (!onError) {\n throw error;\n }\n\n onError(error);\n }\n }\n }\n } while (updated);\n}\n","import { after, arrayRemove, facade, required } from '@noeldemartin/utils';\nimport { App } from '@aerogel/core';\nimport { type SolidModel, isContainer } from 'soukai-solid';\n\nimport { getContainedModels } from '@aerogel/plugin-local-first/lib/inference';\n\nconst Cloud = required(() => App.service('$cloud'));\n\nclass SyncQueue {\n\n private models: Set<SolidModel> = new Set();\n private promises: Promise<unknown>[] = [];\n\n public push(model: SolidModel): void {\n this.models.add(model);\n this.syncAfter(after({ seconds: 1 }));\n }\n\n public clear(models?: SolidModel[]): void {\n if (!models) {\n this.models = new Set();\n\n return;\n }\n\n for (const model of models) {\n this.models.delete(model);\n }\n }\n\n protected async syncAfter<T = void>(operationOrPromise: Promise<T> | (() => Promise<T>)): Promise<T> {\n const promise = typeof operationOrPromise === 'function' ? operationOrPromise() : operationOrPromise;\n\n this.promises.push(promise);\n\n promise.then(() => arrayRemove(this.promises, promise));\n\n if (this.promises.length === 1) {\n this.schedule();\n }\n\n return promise as Promise<T>;\n }\n\n private schedule(): void {\n Promise.all(this.promises)\n .then(() => after())\n .then(() => {\n if (this.promises.length !== 0) {\n this.schedule();\n\n return;\n }\n\n const models = this.consume();\n\n if (models.length === 0) {\n return;\n }\n\n Cloud.syncIfOnline(models);\n });\n }\n\n private consume(): SolidModel[] {\n const models: SolidModel[] = [];\n const children: Set<SolidModel> = new Set();\n\n for (const model of this.models) {\n if (!isContainer(model)) {\n continue;\n }\n\n this.models.delete(model);\n getContainedModels(model).forEach((child) => children.add(child));\n models.push(model);\n }\n\n for (const model of this.models) {\n this.models.delete(model);\n\n if (children.has(model)) {\n continue;\n }\n\n models.push(model);\n }\n\n return models;\n }\n\n}\n\nexport default facade(SyncQueue);\n","import { bootModels } from 'soukai';\nimport { fail, requireUrlParentDirectory, required, tap, urlResolveDirectory, urlRoute } from '@noeldemartin/utils';\nimport { App } from '@aerogel/core';\nimport { getTrackedModels, trackModelsCollection as trackSoukaiModelsCollection } from '@aerogel/plugin-soukai';\nimport { Solid } from '@aerogel/plugin-solid';\nimport { PropertyOperation, SolidContainer, Tombstone, isContainerClass } from 'soukai-solid';\nimport type {\n Operation,\n SolidContainsRelation,\n SolidModel,\n SolidModelConstructor,\n SolidSchemaDefinition,\n} from 'soukai-solid';\nimport type { ObjectsMap } from '@noeldemartin/utils';\nimport type { Attributes } from 'soukai';\n\nimport SyncQueue from '@aerogel/plugin-local-first/lib/SyncQueue';\nimport { getContainerRelations, getRelatedAppModels } from '@aerogel/plugin-local-first/lib/inference';\n\ninterface CloneOptions {\n clean?: boolean;\n}\n\nconst Cloud = required(() => App.service('$cloud'));\nconst remoteClasses: WeakMap<SolidModelConstructor, SolidModelConstructor> = new WeakMap();\nconst localClasses: WeakMap<SolidModelConstructor, SolidModelConstructor> = new WeakMap();\nconst cloneConstructors: WeakMap<SolidModelConstructor, [typeof SolidModel, typeof SolidModel][]> = new WeakMap();\n\nfunction getRelationClasses(modelClass: typeof SolidModel, visited?: Set<typeof SolidModel>): Set<typeof SolidModel> {\n visited ??= new Set();\n\n if (!visited.has(modelClass)) {\n visited.add(modelClass);\n\n for (const relation of modelClass.relations) {\n getRelationClasses(modelClass.instance().requireRelation(relation).relatedClass, visited);\n }\n }\n\n return visited;\n}\n\nfunction cleanRemoteModelClone(remoteModel: SolidModel): void {\n const relatedModels = remoteModel.getRelatedModels().concat([remoteModel]);\n\n for (const relatedModel of relatedModels) {\n relatedModel.cleanDirty(true);\n }\n}\n\nfunction fixRemoteModelClone(remoteModel: SolidModel): void {\n const relatedModels = getRelatedAppModels(remoteModel).concat([remoteModel]);\n\n for (const relatedModel of relatedModels) {\n if (!relatedModel.operations || relatedModel.operations.length === 0) {\n continue;\n }\n\n const operations = (relatedModel.operations ?? []).filter((operation) => {\n return (\n !(operation instanceof PropertyOperation) ||\n !relatedModel.ignoreRdfPropertyHistory(operation.property, true)\n );\n });\n\n if (!operations.some((operation) => !operation.isInception(relatedModel))) {\n relatedModel.setRelationModels('operations', []);\n\n continue;\n }\n\n relatedModel.setRelationModels('operations', operations);\n }\n}\n\nexport async function createRemoteModel(localModel: SolidModel): Promise<void> {\n Cloud.setState({\n localModelUpdates: {\n ...Cloud.localModelUpdates,\n [localModel.url]: 1,\n },\n });\n\n if (isRegisteredModelClass(localModel.static())) {\n await trackModelsCollection(localModel.static(), requireUrlParentDirectory(localModel.url));\n }\n\n if (Cloud.autoPush && Cloud.ready && !Cloud.syncing) {\n SyncQueue.push(localModel);\n }\n}\n\nexport function createRemoteContainer(remoteModel: SolidModel, localModels: ObjectsMap<SolidModel>): SolidContainer {\n const RemoteContainer = getRemoteClass(SolidContainer);\n const path = Cloud.registeredModels.find(\n ({ modelClass: registeredModelClass }) => registeredModelClass === remoteModel.static(),\n )?.path;\n\n return new RemoteContainer({\n url: getRemoteContainersCollection(getLocalModel(remoteModel, localModels).static(), path),\n });\n}\n\nexport async function trackModelsCollection(modelClass: SolidModelConstructor, collection: string): Promise<void> {\n if (Cloud.modelCollections[modelClass.modelName]?.includes(collection)) {\n return;\n }\n\n Cloud.setState('modelCollections', {\n ...Cloud.modelCollections,\n [modelClass.modelName]: (Cloud.modelCollections[modelClass.modelName] ?? []).concat(collection),\n });\n\n await trackSoukaiModelsCollection(modelClass, collection);\n}\n\nexport async function updateRemoteModel(localModel: SolidModel): Promise<void> {\n if (ignoreModelUpdates(localModel)) {\n return;\n }\n\n const modelUpdates = Cloud.localModelUpdates[localModel.url] ?? 0;\n\n Cloud.setState({\n localModelUpdates: {\n ...Cloud.localModelUpdates,\n [localModel.url]: localModel.isSoftDeleted() ? 1 : modelUpdates + 1,\n },\n });\n\n await Cloud.getDocumentsCache().forget(\n requireUrlParentDirectory(localModel.requireDocumentUrl()),\n localModel.requireDocumentUrl(),\n );\n\n if (Cloud.autoPush && Cloud.ready && !Cloud.syncing) {\n SyncQueue.push(localModel);\n }\n}\n\nexport function clearLocalModelUpdates(syncedModelUrls: Set<string>, documentsWithErrors?: Set<string>): void {\n const localModelUpdates = {} as Record<string, number>;\n const syncedModelUrlsArray = Array.from(syncedModelUrls);\n\n for (const [url, count] of Object.entries(Cloud.localModelUpdates)) {\n const documentUrl = urlRoute(url);\n const wasSynced =\n syncedModelUrls.has(url) ||\n syncedModelUrlsArray.some((modelUrl) => modelUrl.endsWith('/') && url.startsWith(modelUrl));\n\n if (wasSynced && !documentsWithErrors?.has(documentUrl)) {\n continue;\n }\n\n localModelUpdates[url] = count;\n }\n\n Cloud.setState({ localModelUpdates });\n}\n\nexport function cloneLocalModel(localModel: SolidModel, options: CloneOptions = {}): SolidModel {\n const constructors = Array.from(new Set(getRelatedAppModels(localModel).map((model) => model.static()))).map(\n (localClass) => [localClass, getRemoteClass(localClass)] as [typeof SolidModel, typeof SolidModel],\n );\n\n return tap(localModel.clone({ constructors }), (model) => {\n fixRemoteModelClone(model);\n\n options.clean && cleanRemoteModelClone(model);\n });\n}\n\nexport function cloneRemoteModel(remoteModel: SolidModel): SolidModel {\n return remoteModel.clone({ constructors: getCloneConstructors(remoteModel) });\n}\n\nexport async function completeRemoteModels(\n localModels: SolidModel[],\n remoteModels: SolidModel[],\n documentsWithErrors: Set<string>,\n): Promise<SolidModel[]> {\n const RemoteTombstone = getRemoteClass(Tombstone);\n const remoteModelUrls = remoteModels.map((remoteModel) => remoteModel.url);\n const missingModelDocumentUrls = localModels\n .filter((localModel) => !remoteModelUrls.includes(localModel.url))\n .map((localModel) => localModel.requireDocumentUrl())\n .filter((documentUrl) => !documentsWithErrors.has(documentUrl));\n const tombstones = await RemoteTombstone.all({ $in: missingModelDocumentUrls });\n\n return remoteModels.concat(tombstones);\n}\n\nexport function ignoreModelUpdates(localModel: SolidModel): boolean {\n const documentModels = localModel.getDocumentModels();\n const documentOperations = documentModels.flatMap(\n (model) => model.operations?.map((operation) => [model, operation] as [SolidModel, Operation]) ?? [],\n );\n\n return !documentOperations.some(([model, operation]) => {\n if (operation.date.getTime() !== model.metadata?.updatedAt?.getTime()) {\n return false;\n }\n\n if (!(operation instanceof PropertyOperation)) {\n return true;\n }\n\n return !model.ignoreRdfPropertyHistory(operation.property, true);\n });\n}\n\nexport function getCloneConstructors(model: SolidModel): [typeof SolidModel, typeof SolidModel][] {\n const modelClass = model.static();\n\n if (!cloneConstructors.has(modelClass)) {\n const constructors = Array.from(getRelationClasses(modelClass))\n .map((otherClass) =>\n isRemoteModelClass(otherClass)\n ? [otherClass, getLocalClass(otherClass)]\n : [otherClass, getRemoteClass(otherClass)])\n .map(([a, b]) => [\n [a, b] as [typeof SolidModel, typeof SolidModel],\n [b, a] as [typeof SolidModel, typeof SolidModel],\n ])\n .flat();\n\n for (const constructor of constructors) {\n cloneConstructors.set(constructor[0], constructors);\n }\n }\n\n return required(cloneConstructors.get(modelClass));\n}\n\nexport function getLocalModel(remoteModel: SolidModel, localModels: ObjectsMap<SolidModel>): SolidModel {\n return localModels.get(remoteModel.url) ?? cloneRemoteModel(remoteModel);\n}\n\nexport function getLocalModels(): SolidModel[] {\n return [...Cloud.registeredModels]\n .map(({ modelClass }) => getTrackedModels(modelClass, { includeSoftDeleted: true }))\n .flat();\n}\n\nexport function getSchemaMigrations(): Map<SolidModelConstructor, SolidModelConstructor | SolidSchemaDefinition> {\n return Cloud.schemaMigrations;\n}\n\nexport function clearSchemaMigrations(): void {\n Cloud.schemaMigrations.clear();\n}\n\nexport function getSchemaMigration(\n modelClass: SolidModelConstructor,\n): SolidModelConstructor | SolidSchemaDefinition | undefined {\n return Cloud.schemaMigrations.get(modelClass);\n}\n\nexport function getRemoteClass<T extends SolidModelConstructor>(localClass: T): T {\n return (remoteClasses.get(localClass) as T) ?? makeRemoteClass(localClass);\n}\n\nexport function getRemoteContainersCollection(modelClass: SolidModelConstructor, path?: string): string {\n const rootStorage = Solid.requireUser().storageUrls[0];\n const containedClass =\n isContainerClass(modelClass) &&\n getContainerRelations(modelClass)\n .map((relation) => {\n const relatedClass = modelClass\n .instance()\n .requireRelation<SolidContainsRelation>(relation).relatedClass;\n\n if (isContainerClass(relatedClass)) {\n return null;\n }\n\n return relatedClass;\n })\n .filter(Boolean)[0];\n\n path ??= `/${(containedClass || modelClass).modelName.toLowerCase()}s/`;\n\n return urlResolveDirectory((path.startsWith('/') ? rootStorage.slice(0, -1) : rootStorage) + path);\n}\n\nexport function getRemoteModel(localModel: SolidModel, remoteModels: ObjectsMap<SolidModel>): SolidModel {\n return remoteModels.get(localModel.url) ?? cloneLocalModel(localModel);\n}\n\nexport function isRegisteredModel(model: SolidModel): boolean {\n for (const { modelClass } of Cloud.registeredModels) {\n const models = getTrackedModels(modelClass);\n\n if (models.some((registeredModel) => registeredModel.url === model.url)) {\n return true;\n }\n }\n\n return false;\n}\n\nexport function isRemoteModel(model: SolidModel): boolean {\n return isRemoteModelClass(model.static());\n}\n\nexport function isRemoteModelClass(modelClass: typeof SolidModel): boolean {\n return localClasses.has(modelClass);\n}\n\nexport function isLocalModel(model: SolidModel): boolean {\n return !isRemoteModel(model);\n}\n\nexport function isRegisteredModelClass(modelClass: SolidModelConstructor): boolean {\n return Cloud.registeredModels.some(({ modelClass: registeredModelClass }) => registeredModelClass === modelClass);\n}\n\nexport function makeRemoteClass<T extends SolidModelConstructor>(localClass: T): T {\n const LocalClass = localClass as typeof SolidModel;\n const withLocalHistoryConfig = (modelClass: typeof SolidModel, operation: () => unknown) => {\n modelClass.timestamps = LocalClass.timestamps;\n modelClass.history = LocalClass.history;\n\n operation();\n\n modelClass.timestamps = [];\n modelClass.history = false;\n };\n const RemoteClass = class extends LocalClass {\n\n public static override timestamps = false;\n public static override history = false;\n\n protected override initialize(attributes: Attributes, exists: boolean): void {\n withLocalHistoryConfig(this._proxy.static(), () => super.initialize(attributes, exists));\n }\n\n protected override initializeRelations(): void {\n super.initializeRelations();\n\n for (const relation of Object.values(this._relations)) {\n relation.relatedClass = getRemoteClass(relation.relatedClass);\n }\n }\n\n public override fixMalformedAttributes(): void {\n withLocalHistoryConfig(this.static(), () => super.fixMalformedAttributes());\n }\n \n } as unknown as T;\n\n LocalClass.on('schema-updated', async (schema) => {\n await RemoteClass.updateSchema({\n ...schema,\n timestamps: false,\n history: false,\n });\n });\n\n localClass.ensureBooted();\n bootModels({ [`Remote${localClass.modelName}`]: RemoteClass });\n App.service('$cloud') && Cloud.getEngine() && RemoteClass.setEngine(Cloud.requireEngine());\n\n remoteClasses.set(LocalClass, RemoteClass);\n localClasses.set(RemoteClass, LocalClass);\n\n return RemoteClass;\n}\n\nexport function getLocalClass<T extends SolidModelConstructor>(remoteClass: T): T {\n return (localClasses.get(remoteClass) as T) ?? fail(`Couldn't find local class for ${remoteClass.modelName}`);\n}\n","import { Job } from '@aerogel/core';\nimport { requireEngine } from 'soukai';\nimport { requireUrlParentDirectory } from '@noeldemartin/utils';\nimport { ignoreModelsCollection, trackModelsCollection } from '@aerogel/plugin-soukai';\nimport { Solid } from '@aerogel/plugin-solid';\nimport type { EngineDocument, IndexedDBEngine } from 'soukai';\nimport type { SolidModelConstructor } from 'soukai-solid';\n\ninterface Migration {\n modelClass: SolidModelConstructor;\n local: string;\n remote: string;\n}\n\nexport default class Backup extends Job {\n\n private urlMigrations: Migration[] = [];\n private collectionMigrations: Migration[] = [];\n\n public migrateUrl(modelClass: SolidModelConstructor, local: string, remote: string): void {\n this.urlMigrations.push({\n modelClass,\n local,\n remote,\n });\n }\n\n public migrateCollection(modelClass: SolidModelConstructor, local: string, remote: string): void {\n this.collectionMigrations.push({\n modelClass,\n local,\n remote,\n });\n }\n\n protected async run(): Promise<void> {\n const engine = requireEngine<IndexedDBEngine>();\n const collections = await engine.getCollections();\n const droppedCollections = new Set<string>();\n\n for (const collection of collections) {\n const documents = await engine.readMany(collection);\n\n for (const [localUrl, document] of Object.entries(documents)) {\n const remoteUrl = this.replaceUrl(localUrl);\n\n await engine.create(\n requireUrlParentDirectory(remoteUrl),\n this.replaceDocumentUrls(document),\n remoteUrl,\n );\n\n await engine.delete(collection, localUrl);\n }\n }\n\n for (const { modelClass, remote } of this.urlMigrations) {\n trackModelsCollection(modelClass, requireUrlParentDirectory(remote));\n }\n\n for (const { modelClass, local, remote } of this.collectionMigrations) {\n const solidCollections = Object.assign({}, Solid.collections);\n const filteredCollections = (Solid.collections[modelClass.modelName] ?? []).filter(\n (collection) => !local.startsWith(collection),\n );\n\n ignoreModelsCollection(modelClass, local);\n trackModelsCollection(modelClass, remote);\n\n for (const localCollection of Solid.collections[modelClass.modelName] ?? []) {\n const remoteCollection = this.replaceUrl(localCollection);\n\n if (remoteCollection !== localCollection) {\n ignoreModelsCollection(modelClass, localCollection);\n trackModelsCollection(modelClass, remoteCollection);\n }\n }\n\n Solid.collections = solidCollections;\n\n collections\n .filter((collection) => local.startsWith(collection))\n .forEach((collection) => droppedCollections.add(collection));\n\n if (filteredCollections.length > 0) {\n solidCollections[modelClass.modelName] = filteredCollections;\n } else {\n delete solidCollections[modelClass.modelName];\n }\n }\n\n await engine.dropCollections(Array.from(droppedCollections));\n }\n\n protected replaceDocumentUrls(document: EngineDocument): EngineDocument {\n for (const [key, value] of Object.entries(document)) {\n if (key === '@id' && typeof value === 'string') {\n document[key] = this.replaceUrl(value);\n\n continue;\n }\n\n if (typeof value !== 'object' || value === null) {\n continue;\n }\n\n document[key] = this.replaceDocumentUrls(value as EngineDocument);\n }\n\n return document;\n }\n\n protected replaceUrl(url: string): string {\n for (const { local, remote } of this.urlMigrations) {\n if (!url.startsWith(local)) {\n continue;\n }\n\n return url.replace(local, remote);\n }\n\n for (const { local, remote } of this.collectionMigrations) {\n if (!url.startsWith(local)) {\n continue;\n }\n\n return url.replace(local, remote);\n }\n\n return url;\n }\n\n}\n","export function mapFromArray<K, V>(items: [K, V][]): Map<K, V> {\n const itemsMap = new Map();\n\n for (const [key, value] of items) {\n itemsMap.set(key, value);\n }\n\n return itemsMap;\n}\n\nexport function lazy<T>(getter: () => Promise<T>): () => Promise<T> {\n const result: { value?: T } = {};\n\n return async () => {\n if (!('value' in result)) {\n result.value = await getter();\n }\n\n return result.value as T;\n };\n}\n","import { arrayChunk, arrayFrom, isInstanceOf, map, requireUrlParentDirectory, required } from '@noeldemartin/utils';\nimport { DocumentNotFound, type EngineDocument } from 'soukai';\nimport { Tombstone } from 'soukai-solid';\nimport type { JobStatus } from '@aerogel/core';\nimport type { ObjectsMap } from '@noeldemartin/utils';\nimport type { SolidContainer, SolidContainsRelation, SolidDocument, SolidModel } from 'soukai-solid';\n\nimport { isLocalModel, isRemoteModel } from '@aerogel/plugin-local-first/lib/mirroring';\nimport { getContainerRelations } from '@aerogel/plugin-local-first/lib/inference';\nimport { lazy } from '@aerogel/plugin-local-first/lib/utils';\n\nexport interface ResourceJobStatus extends JobStatus {\n documentUrl?: string;\n children?: ResourceJobStatus[];\n}\n\nexport default class LoadsChildren {\n\n declare protected localModels?: ObjectsMap<SolidModel>;\n\n protected async loadContainedModels(\n container: SolidContainer,\n options: {\n ignoreTombstones?: boolean;\n status?: ResourceJobStatus;\n updateProgress?: (update?: () => unknown) => Promise<void>;\n onDocumentLoaded?: () => unknown;\n onDocumentError?: (error: unknown) => unknown;\n onDocumentRead?: (document: SolidDocument) => unknown;\n onDocumentIgnored?: (document: SolidDocument) => unknown;\n } = {},\n ): Promise<SolidModel[]> {\n if (isLocalModel(container)) {\n const children = [];\n\n for (const relation of getContainerRelations(container.static())) {\n const relationModels =\n (await container.loadRelationIfUnloaded<SolidModel | SolidModel[] | null>(relation)) ?? [];\n\n children.push(...arrayFrom(relationModels));\n }\n\n return children;\n }\n\n const children: Record<string, SolidModel[]> = {};\n const tombstones: Tombstone[] = [];\n const resourceUrlChunks = arrayChunk(container.resourceUrls, 10);\n const statusChildren = resourceUrlChunks.flat().map((url) => ({\n documentUrl: url,\n completed: false,\n }));\n const statusChildrenMap = map(statusChildren, 'documentUrl');\n const updateProgress = options.updateProgress ?? ((operation) => Promise.resolve(operation?.()));\n\n if (options.status) {\n options.status.children = statusChildren;\n }\n\n for (const resourceUrls of resourceUrlChunks) {\n await Promise.all(\n resourceUrls.map(async (resourceUrl) => {\n if (\n container.resources.some(\n (resource) =>\n resource.url === resourceUrl &&\n resource.types.some((type) =>\n type.startsWith('http://www.w3.org/ns/iana/media-types/image/')),\n )\n ) {\n return;\n }\n\n const { children: documentChildren, tombstones: documentTombstones } =\n await this.loadDocumentChildren(container, resourceUrl, options);\n\n tombstones.push(...documentTombstones);\n\n for (const [relation, documentModels] of Object.entries(documentChildren)) {\n const relationChildren = (children[relation] ??= []);\n\n relationChildren.push(...documentModels);\n }\n\n if (resourceUrl.endsWith('/')) {\n return;\n }\n\n await updateProgress(() => {\n required(statusChildrenMap.get(resourceUrl)).completed = true;\n });\n\n await options.onDocumentLoaded?.();\n }),\n );\n }\n\n for (const [relation, relationModels] of Object.entries(children)) {\n container.setRelationModels(relation, relationModels);\n }\n\n const childrenArray = options.ignoreTombstones\n ? Object.values(children).flat()\n : Object.values(children).flat().concat(tombstones);\n\n await updateProgress(() => {\n if (!options.status) {\n return;\n }\n\n options.status.children = childrenArray.map((child) => {\n return required(statusChildrenMap.get(child.requireDocumentUrl()));\n });\n });\n\n return childrenArray;\n }\n\n protected async loadContainedDocuments(\n container: SolidContainer,\n options: {\n status?: ResourceJobStatus;\n updateProgress?: (update?: () => unknown) => Promise<void>;\n onDocumentLoaded?: () => unknown;\n onDocumentError?: (error: unknown) => unknown;\n onDocumentRead?: (document: SolidDocument) => unknown;\n } = {},\n ): Promise<Record<string, EngineDocument>> {\n if (!isRemoteModel(container)) {\n throw Error('Cannot get contained models from local model');\n }\n\n const engineDocuments: Record<string, EngineDocument> = {};\n const remoteEngine = container.requireEngine();\n const resourceUrlChunks = arrayChunk(container.resourceUrls, 10);\n const statusChildren = resourceUrlChunks.flat().map((url) => ({\n documentUrl: url,\n completed: false,\n }));\n const statusChildrenMap = map(statusChildren, 'documentUrl');\n const updateProgress = options.updateProgress ?? ((operation) => Promise.resolve(operation?.()));\n\n if (options.status) {\n options.status.children = statusChildren;\n }\n\n for (const resourceUrls of resourceUrlChunks) {\n await Promise.all(\n resourceUrls.map(async (resourceUrl) => {\n if (\n !resourceUrl ||\n resourceUrl.endsWith('/') ||\n container.resources.some(\n (resource) =>\n resource.url === resourceUrl &&\n resource.types.some((type) =>\n type.startsWith('http://www.w3.org/ns/iana/media-types/image/')),\n )\n ) {\n await updateProgress(() => {\n required(statusChildrenMap.get(resourceUrl)).completed = true;\n });\n\n return;\n }\n\n const document = container.documents.find(({ url }) => url === resourceUrl);\n\n try {\n engineDocuments[resourceUrl] = await remoteEngine.readOne(container.url, resourceUrl);\n } catch (error) {\n if (!options.onDocumentError) {\n throw error;\n }\n\n await options.onDocumentError?.(error);\n }\n\n if (document) {\n await options.onDocumentRead?.(document);\n }\n\n await updateProgress(() => {\n required(statusChildrenMap.get(resourceUrl)).completed = true;\n });\n\n await options.onDocumentLoaded?.();\n }),\n );\n }\n\n return engineDocuments;\n }\n\n private async loadDocumentChildren(\n container: SolidContainer,\n documentUrl: string,\n options: {\n onDocumentError?: (error: unknown) => unknown;\n onDocumentRead?: (document: SolidDocument) => unknown;\n onDocumentIgnored?: (document: SolidDocument) => unknown;\n } = {},\n ): Promise<{ children: Record<string, SolidModel[]>; tombstones: Tombstone[] }> {\n return this.loadDocumentChildrenFromRemote(container, documentUrl, options);\n }\n\n private async loadDocumentChildrenFromRemote(\n container: SolidContainer,\n documentUrl: string,\n options: {\n onDocumentError?: (error: unknown) => unknown;\n onDocumentRead?: (document: SolidDocument) => unknown;\n onDocumentIgnored?: (document: SolidDocument) => unknown;\n } = {},\n ): Promise<{ children: Record<string, SolidModel[]>; tombstones: Tombstone[] }> {\n const children: Record<string, SolidModel[]> = {};\n const tombstones: Tombstone[] = [];\n const readDocument = lazy(async () => {\n try {\n const documentModel = container.documents.find((document) => document.url === documentUrl);\n const document = await container\n .requireEngine()\n .readOne(requireUrlParentDirectory(documentUrl), documentUrl);\n const documentTombstones = await Tombstone.createManyFromEngineDocuments({\n [documentUrl]: document,\n });\n\n tombstones.push(...documentTombstones);\n\n if (documentModel) {\n options.onDocumentRead?.(documentModel);\n }\n\n return document;\n } catch (error) {\n if (isInstanceOf(error, DocumentNotFound)) {\n return null;\n }\n\n if (!options.onDocumentError) {\n throw error;\n }\n\n options.onDocumentError(error);\n\n return null;\n }\n });\n\n let found = false;\n\n for (const relation of getContainerRelations(container.static())) {\n const relationInstance = container.requireRelation<SolidContainsRelation>(relation);\n\n if (relationInstance.loaded) {\n children[relation] = relationInstance.getLoadedModels();\n\n continue;\n }\n\n const document = await readDocument();\n\n if (!document) {\n continue;\n }\n\n try {\n const documentChildren = await relationInstance.relatedClass.createManyFromEngineDocuments({\n [documentUrl]: document,\n });\n\n children[relation] = documentChildren;\n\n found ||= documentChildren.length > 0;\n } catch (error) {\n if (!options.onDocumentError) {\n throw error;\n }\n\n options.onDocumentError(error);\n }\n }\n\n if (!found && options.onDocumentIgnored) {\n const documentModel = container.documents.find((document) => document.url === documentUrl);\n\n documentModel && (await options.onDocumentIgnored(documentModel));\n }\n\n return { children, tombstones };\n }\n\n}\n","import { Solid } from '@aerogel/plugin-solid';\nimport type { SolidTypeIndex } from 'soukai-solid';\nimport type { SolidUserProfile } from '@noeldemartin/solid-utils';\n\nconst typeIndexes: WeakMap<SolidUserProfile, SolidTypeIndex | null> = new WeakMap();\n\nexport default class LoadsTypeIndex {\n\n protected async loadTypeIndex(options?: { create?: false; fresh?: boolean }): Promise<SolidTypeIndex | null>;\n protected async loadTypeIndex(options?: { create?: true; fresh?: boolean }): Promise<SolidTypeIndex>;\n protected async loadTypeIndex(options: { create?: boolean; fresh?: boolean } = {}): Promise<SolidTypeIndex | null> {\n const user = Solid.requireUser();\n\n if (options.fresh || !typeIndexes.has(user)) {\n typeIndexes.set(user, await Solid.findPrivateTypeIndex({ fresh: options.fresh }));\n }\n\n if (options.create && !typeIndexes.get(user)) {\n typeIndexes.set(user, await Solid.findOrCreatePrivateTypeIndex());\n }\n\n return typeIndexes.get(user) ?? null;\n }\n\n}\n","import type { ObjectsMap } from '@noeldemartin/utils';\nimport type { SolidModel } from 'soukai-solid';\n\nimport { getRelatedAppModels, loadAppRelations } from '@aerogel/plugin-local-first/lib/inference';\n\nexport default class TracksLocalModels {\n\n declare protected localModels: ObjectsMap<SolidModel>;\n\n protected async indexLocalModels(models: SolidModel[]): Promise<void> {\n for (const localModel of models) {\n await this.addLocalModel(localModel);\n }\n }\n\n protected async addLocalModel(localModel: SolidModel): Promise<void> {\n if (this.localModels.hasKey(localModel.url)) {\n return;\n }\n\n this.localModels.add(localModel);\n\n await loadAppRelations(localModel);\n\n for (const relatedModel of getRelatedAppModels(localModel)) {\n await this.addLocalModel(relatedModel);\n }\n }\n\n}\n","import { PropertyOperation, isContainer } from 'soukai-solid';\nimport { Job } from '@aerogel/core';\nimport { isInstanceOf, map, mixed, objectMap, tap } from '@noeldemartin/utils';\nimport type { JobListener, JobStatus } from '@aerogel/core';\nimport type { Nullable } from '@noeldemartin/utils';\nimport type { SolidModel, SolidTypeIndex } from 'soukai-solid';\n\nimport {\n clearSchemaMigrations,\n getRemoteClass,\n getSchemaMigration,\n getSchemaMigrations,\n} from '@aerogel/plugin-local-first/lib/mirroring';\nimport { getContainerRegisteredClasses } from '@aerogel/plugin-local-first/lib/inference';\n\nimport LoadsChildren from './mixins/LoadsChildren';\nimport LoadsTypeIndex from './mixins/LoadsTypeIndex';\nimport TracksLocalModels from './mixins/TracksLocalModels';\n\nconst BaseJob = Job as typeof Job<JobListener, MigrateJobStatus, MigrateJobStatus>;\n\nexport interface MigrateJobStatus extends JobStatus {\n children?: MigrateModelJobStatus[];\n}\n\nexport interface MigrateModelJobStatus extends JobStatus {\n modelUrl: string;\n children?: MigrateModelJobStatus[];\n}\n\nexport default class Migrate extends mixed(BaseJob, [LoadsChildren, LoadsTypeIndex, TracksLocalModels]) {\n\n public static restore(status: MigrateJobStatus): Migrate {\n return tap(new Migrate(), (job) => {\n job.status = status;\n });\n }\n\n constructor() {\n super();\n\n this.localModels = map([], 'url');\n }\n\n protected _models?: SolidModel[];\n\n public get models(): SolidModel[] | undefined {\n return this._models;\n }\n\n public set models(models: SolidModel[] | undefined) {\n if (!models) {\n delete this._models;\n\n this.localModels = map([], 'url');\n\n return;\n }\n\n const childrenStatus = objectMap(this.status.children ?? [], 'modelUrl');\n\n this._models = models;\n this.localModels = map([], 'url');\n this.status.children = models.map(\n (model) =>\n childrenStatus[model.url] ?? {\n modelUrl: model.url,\n completed: false,\n },\n );\n }\n\n protected async run(): Promise<void> {\n if (!this.models) {\n throw new Error('Cant start migration without models');\n }\n\n await this.indexLocalModels(this.models);\n\n const modelStatuses = this.status.children ?? [];\n const typeIndex = await this.loadTypeIndex();\n\n for (const modelStatus of modelStatuses) {\n const model = this.models.find(({ url }) => modelStatus.modelUrl === url);\n\n if (!model || modelStatus.completed) {\n continue;\n }\n\n await this.migrateRegisteredModel(model, modelStatus, typeIndex);\n await this.updateProgress(() => (modelStatus.completed = true));\n }\n\n for (const [modelClass, schema] of getSchemaMigrations()) {\n await modelClass.updateSchema(schema);\n }\n\n clearSchemaMigrations();\n }\n\n protected async migrateRegisteredModel(\n model: SolidModel,\n status: MigrateModelJobStatus,\n typeIndex?: Nullable<SolidTypeIndex>,\n ): Promise<void> {\n await this.migrate(model, status);\n\n if (!isContainer(model)) {\n return;\n }\n\n const registeredClasses = getContainerRegisteredClasses(model.static());\n const registration = typeIndex?.registrations.find(({ instanceContainer }) => instanceContainer === model.url);\n\n if (!typeIndex || !registration || registeredClasses.length === 0) {\n return;\n }\n\n registration.setAttribute(\n 'forClass',\n registeredClasses\n .map((modelClass) => getSchemaMigration(modelClass)?.rdfsClasses ?? modelClass.rdfsClass)\n .flat(),\n );\n\n await typeIndex.save();\n }\n\n protected async migrate(localModel: SolidModel, status: MigrateModelJobStatus): Promise<void> {\n this.assertNotCancelled();\n\n await this.migrateChildren(localModel, status);\n\n const schema = getSchemaMigration(localModel.static());\n\n if (!schema) {\n return;\n }\n\n const remoteModel = await getRemoteClass(localModel.static()).find(localModel.url);\n const migratedModel = await remoteModel?.migrateSchema(schema);\n\n await localModel.migrateSchema(schema, {\n mintOperationUrl: (operation) => {\n return migratedModel?.operations?.find((migratedOperation) => {\n if (\n !isInstanceOf(operation, PropertyOperation) ||\n !isInstanceOf(migratedOperation, PropertyOperation)\n ) {\n return false;\n }\n\n return (\n operation.property === migratedOperation.property &&\n operation.date.getTime() === migratedOperation.date.getTime()\n );\n })?.url;\n },\n });\n }\n\n protected async migrateChildren(localModel: SolidModel, status: MigrateModelJobStatus): Promise<void> {\n if (!isContainer(localModel)) {\n return;\n }\n\n const children = await this.loadContainedModels(localModel, { ignoreTombstones: true });\n\n status.children ??= children.map((child) => ({\n modelUrl: child.url,\n completed: false,\n }));\n\n for (const childStatus of status.children) {\n const child = children.find(({ url }) => childStatus.modelUrl === url);\n\n if (!child || childStatus.completed) {\n continue;\n }\n\n await this.migrate(child, childStatus);\n await this.updateProgress(() => (childStatus.completed = true));\n }\n }\n\n}\n","import {\n arrayWithout,\n isInstanceOf,\n map,\n mixed,\n requireUrlParentDirectory,\n required,\n round,\n toString,\n urlRoute,\n} from '@noeldemartin/utils';\nimport { App, Errors, Job } from '@aerogel/core';\nimport { DocumentNotFound, InvalidModelAttributes, requireBootedModel, requireEngine } from 'soukai';\nimport { MalformedSolidDocumentError } from '@noeldemartin/solid-utils';\nimport { Solid } from '@aerogel/plugin-solid';\nimport { SolidContainer, SolidModel, Tombstone, isContainer, isContainerClass } from 'soukai-solid';\nimport type { ObjectsMap } from '@noeldemartin/utils';\nimport type { JobListener, JobStatus } from '@aerogel/core';\nimport type { SolidContainsRelation, SolidEngine, SolidModelConstructor, SolidTypeIndex } from 'soukai-solid';\n\nimport {\n clearLocalModelUpdates,\n cloneLocalModel,\n cloneRemoteModel,\n completeRemoteModels,\n createRemoteContainer,\n getCloneConstructors,\n getLocalModel,\n getLocalModels,\n getRemoteClass,\n getRemoteModel,\n isRegisteredModel,\n isRemoteModel,\n trackModelsCollection,\n} from '@aerogel/plugin-local-first/lib/mirroring';\nimport {\n getContainerRegisteredClasses,\n getContainerRelations,\n getRelatedAppModels,\n isDirtyOrHasDirtyChildren,\n loadAppRelations,\n} from '@aerogel/plugin-local-first/lib/inference';\n\nimport LoadsChildren from './mixins/LoadsChildren';\nimport LoadsTypeIndex from './mixins/LoadsTypeIndex';\nimport TracksLocalModels from './mixins/TracksLocalModels';\nimport type { ResourceJobStatus } from './mixins/LoadsChildren';\n\nconst Cloud = required(() => App.service('$cloud'));\nconst BaseJob = Job as typeof Job<JobListener, SyncJobStatus, SyncJobStatus>;\n\ninterface SyncJobStatus extends JobStatus {\n root: true;\n children: [SyncPullJobStatus, JobStatus];\n}\n\ninterface SyncPullJobStatus extends JobStatus {\n children?: ResourceJobStatus[];\n}\n\nfunction isRootStatus(status?: JobStatus): status is SyncJobStatus {\n return !!status && 'root' in status;\n}\n\nexport default class Sync extends mixed(BaseJob, [LoadsChildren, LoadsTypeIndex, TracksLocalModels]) {\n\n public readonly documentsWithErrors: Set<string>;\n protected models?: SolidModel[];\n protected dirtyRemoteModels?: SolidModel[];\n protected rootLocalModels: SolidModel[];\n protected tombstones: ObjectsMap<Tombstone>;\n protected syncedModelUrls: Set<string>;\n protected documentsModifiedAt: Record<string, Date>;\n protected screenLock: Promise<void | { release(): Promise<void> }> | null = null;\n protected override localModels: ObjectsMap<SolidModel>;\n\n constructor(models?: SolidModel[]) {\n super();\n\n this.documentsWithErrors = new Set();\n this.models = models;\n this.rootLocalModels = [];\n this.localModels = map([], 'url');\n this.tombstones = map([], 'resourceUrl');\n this.syncedModelUrls = new Set();\n this.documentsModifiedAt = {};\n }\n\n protected async run(): Promise<void> {\n const engine = Solid.requireAuthenticator().engine as SolidEngine;\n const updateDocumentDate = (url: string, { headers }: { headers?: Headers }, fallbackDate?: Date) => {\n const date = headers?.get('last-modified') ?? fallbackDate;\n\n if (!date || url.endsWith('/')) {\n return;\n }\n\n this.documentsModifiedAt[url] = new Date(date);\n };\n const clearListener = engine.listeners.add({\n onDocumentRead: (url, metadata) => updateDocumentDate(url, metadata),\n onDocumentUpdated: (url, metadata) => updateDocumentDate(url, metadata, new Date()),\n });\n\n try {\n this.lockScreen();\n this.rootLocalModels = this.models ?? getLocalModels();\n\n engine.setConfig({ cachesDocuments: true, persistentCache: Cloud.getDocumentsCache() });\n\n await this.indexLocalModels(this.rootLocalModels);\n await this.pullChanges();\n await this.pushChanges();\n } finally {\n engine.clearCache();\n engine.setConfig({ cachesDocuments: false, persistentCache: undefined });\n\n this.releaseScreen();\n clearListener();\n }\n }\n\n protected lockScreen(): void {\n const typedNavigator = navigator as {\n wakeLock?: { request(type?: 'screen'): Promise<{ release(): Promise<void> }> };\n };\n\n if (!typedNavigator.wakeLock) {\n return;\n }\n\n try {\n this.screenLock = typedNavigator.wakeLock.request('screen').catch((error) => {\n Errors.reportDevelopmentError(error, 'Could not request screen wake lock');\n });\n } catch (error) {\n Errors.reportDevelopmentError(error, 'Could not request screen wake lock');\n }\n }\n\n protected releaseScreen(): void {\n if (!this.screenLock) {\n return;\n }\n\n this.screenLock.then((lock) => lock?.release());\n this.screenLock = null;\n }\n\n protected override getInitialStatus(): SyncJobStatus {\n return {\n root: true,\n completed: false,\n children: [{ completed: false }, { completed: false }],\n };\n }\n\n protected override calculateCurrentProgress(status?: JobStatus): number {\n status ??= this.status;\n\n if (isRootStatus(status)) {\n return round(\n this.calculateCurrentProgress(status.children[0]) * 0.9 +\n this.calculateCurrentProgress(status.children[1]) * 0.1,\n 2,\n );\n }\n\n return super.calculateCurrentProgress(status);\n }\n\n private async pullChanges(): Promise<void> {\n const remoteModelsArray = this.models\n ? await this.fetchRemoteModelsForLocal(this.models)\n : await this.fetchRemoteModels();\n const remoteModels = map(remoteModelsArray, (model) => {\n if (model instanceof Tombstone) {\n return model.resourceUrl;\n }\n\n return model.url;\n });\n\n this.dirtyRemoteModels = await this.synchronizeModels(remoteModels);\n\n await this.updateProgress((status) => (status.children[0].completed = true));\n }\n\n private async pushChanges(): Promise<void> {\n const localDocuments = new Set(this.localModels.getItems().map((model) => model.getDocumentUrl()));\n const remoteModels = this.dirtyRemoteModels ?? [];\n const childrenStatus = (this.status.children[1].children = remoteModels.map(() => ({ completed: false })));\n\n for (let index = 0; index < remoteModels.length; index++) {\n const remoteModel = remoteModels[index] as SolidModel;\n const childStatus = childrenStatus[index] as JobStatus;\n\n if (remoteModel.isSoftDeleted()) {\n remoteModel.enableHistory();\n remoteModel.enableTombstone();\n\n await remoteModel.forceDelete();\n await this.updateProgress(() => (childStatus.completed = true));\n\n this.syncedModelUrls.add(remoteModel.url ?? remoteModel.getDeletedPrimaryKey());\n\n continue;\n }\n\n await this.saveModelAndRelated(remoteModel, childStatus);\n await this.updateTypeRegistrations(remoteModel);\n await this.updateProgress(() => (childStatus.completed = true));\n }\n\n const documentsCache = Cloud.getDocumentsCache();\n const tombstoneDocuments = map(this.tombstones.getItems(), (tombstone) => tombstone.requireDocumentUrl());\n\n for (const [documentUrl, modifiedAt] of Object.entries(this.documentsModifiedAt)) {\n if (tombstoneDocuments.hasKey(documentUrl)) {\n const tombstone = tombstoneDocuments.require(documentUrl);\n\n await documentsCache.remember(requireUrlParentDirectory(documentUrl), documentUrl, modifiedAt, {\n tombstone: {\n url: tombstone.url,\n resourceUrl: tombstone.resourceUrl,\n },\n });\n\n continue;\n }\n\n if (localDocuments.has(documentUrl)) {\n await documentsCache.remember(requireUrlParentDirectory(documentUrl), documentUrl, modifiedAt);\n\n continue;\n }\n }\n\n clearLocalModelUpdates(this.syncedModelUrls, this.documentsWithErrors);\n\n await this.updateProgress((status) => (status.children[1].completed = true));\n }\n\n private async fetchRemoteModels(): Promise<SolidModel[]> {\n const pullStatus = this.status.children[0];\n const typeIndex = await this.loadTypeIndex({ fresh: true });\n\n if (!typeIndex) {\n return [];\n }\n\n const remoteModels: SolidModel[] = [];\n const registrations = this.getTypeRegistrations(typeIndex);\n\n pullStatus.children = registrations.map(() => ({ completed: false }));\n\n for (let index = 0; index < registrations.length; index++) {\n const status = required(pullStatus.children?.[index]);\n const { registration, registeredModel } = required(registrations[index]);\n const remoteClass = getRemoteClass(registeredModel.modelClass);\n\n if (!registration.instanceContainer) {\n continue;\n }\n\n Cloud.rootModelCollections[registeredModel.modelClass.modelName] ??= registration.instanceContainer;\n\n if (isContainerClass(remoteClass)) {\n await trackModelsCollection(\n registeredModel.modelClass,\n requireUrlParentDirectory(registration.instanceContainer),\n );\n\n const container = await remoteClass.find(registration.instanceContainer);\n\n if (container) {\n await this.loadChildren(container, status);\n\n remoteModels.push(container);\n }\n\n await this.updateProgress(() => (status.completed = true));\n\n continue;\n }\n\n const containerModels = await this.fetchRemoteModelsFromContainer(\n status,\n registeredModel.modelClass,\n remoteClass,\n registration.instanceContainer,\n );\n\n remoteModels.push(...containerModels);\n\n await this.updateProgress(() => (status.completed = true));\n }\n\n for (const remoteModel of remoteModels) {\n await loadAppRelations(remoteModel, (error) => this.handleDocumentError(error));\n }\n\n return completeRemoteModels(this.rootLocalModels, remoteModels, this.documentsWithErrors);\n }\n\n private async fetchRemoteModelsFromContainer(\n status: ResourceJobStatus,\n localClass: SolidModelConstructor,\n remoteClass: SolidModelConstructor,\n containerUrl: string,\n ): Promise<SolidModel[]> {\n const container = await getRemoteClass(SolidContainer).find(containerUrl);\n\n if (!container) {\n return [];\n }\n\n status.children = container.resourceUrls.map(() => ({ completed: false }));\n\n const documents = await this.loadContainedDocuments(container, {\n status,\n updateProgress: (update) => this.updateProgress(update),\n onDocumentError: (error) => this.handleDocumentError(error),\n onDocumentRead: (document) => {\n if (document.url.endsWith('/') || !document.updatedAt || document.url in this.documentsModifiedAt) {\n return;\n }\n\n this.documentsModifiedAt[document.url] = document.updatedAt;\n },\n onDocumentLoaded: async () => {\n this.assertNotCancelled();\n\n await this.updateProgress();\n },\n });\n\n const remoteModels = await remoteClass.createManyFromEngineDocuments(documents);\n const tombstones = await Tombstone.createManyFromEngineDocuments(documents);\n const documentsCache = Cloud.getDocumentsCache();\n const foundDocuments = new Set(remoteModels.map((model) => model.requireDocumentUrl()));\n\n for (const tombstone of tombstones) {\n this.tombstones.add(tombstone);\n foundDocuments.add(tombstone.requireDocumentUrl());\n }\n\n for (const document of container.documents) {\n if (!document.updatedAt) {\n continue;\n }\n\n if (foundDocuments.has(document.url)) {\n continue;\n }\n\n await documentsCache.remember(requireUrlParentDirectory(document.url), document.url, document.updatedAt);\n\n const engine = requireEngine();\n\n try {\n await engine.readOne(requireUrlParentDirectory(document.url), document.url);\n } catch (error) {\n if (!isInstanceOf(error, DocumentNotFound)) {\n throw error;\n }\n\n // TODO this is causing some pretty nasty bugs!!\n await engine.create(requireUrlParentDirectory(document.url), {}, document.url);\n }\n }\n\n if (remoteModels.length > 0) {\n await trackModelsCollection(localClass, containerUrl);\n }\n\n for (let index = 0; index < container.resourceUrls.length; index++) {\n const resourceUrl = container.resourceUrls[index];\n\n if (!resourceUrl?.endsWith('/')) {\n continue;\n }\n\n const childModels = await this.fetchRemoteModelsFromContainer(\n required(status.children?.[index]),\n localClass,\n remoteClass,\n resourceUrl,\n );\n\n remoteModels.push(...childModels);\n\n await this.updateProgress();\n }\n\n await this.updateProgress(() => (status.completed = true));\n\n return remoteModels;\n }\n\n private async fetchRemoteModelsForLocal(models: SolidModel[]): Promise<SolidModel[]> {\n const remoteModels = [] as SolidModel[];\n const statusChildren = (this.status.children[0].children = models.map(() => ({ completed: false })));\n\n for (let index = 0; index < models.length; index++) {\n await this.ignoringDocumentErrors(async () => {\n const localModel = models[index] as SolidModel;\n const childStatus = statusChildren[index] as JobStatus;\n const remoteModel = await getRemoteClass(localModel.static()).find(localModel.url);\n\n if (!remoteModel) {\n await this.updateProgress(() => (childStatus.completed = true));\n\n return;\n }\n\n isContainer(remoteModel) && (await this.loadChildren(remoteModel, childStatus));\n\n remoteModels.push(remoteModel);\n\n await this.updateProgress(() => (childStatus.completed = true));\n });\n }\n\n for (const remoteModel of remoteModels) {\n await loadAppRelations(remoteModel, (error) => this.handleDocumentError(error));\n }\n\n return completeRemoteModels(models, remoteModels, this.documentsWithErrors);\n }\n\n private getTypeRegistrations(typeIndex: SolidTypeIndex) {\n const processedContainerUrls = new Set();\n const registeredModels = [...Cloud.registeredModels].map(({ modelClass }) => {\n const registeredChildren = isContainerClass(modelClass) ? getContainerRegisteredClasses(modelClass) : [];\n\n return {\n modelClass,\n rdfsClasses:\n registeredChildren.length > 0\n ? registeredChildren.map((childrenClass) => childrenClass.rdfsClasses).flat()\n : modelClass.rdfsClasses,\n };\n });\n const registrations = typeIndex.registrations\n .map((registration) => {\n const registeredModel = registeredModels.find(\n ({ rdfsClasses }) =>\n !!registration.instanceContainer &&\n rdfsClasses.some((rdfsClass) => registration.forClass.includes(rdfsClass)),\n );\n\n if (\n !registeredModel ||\n !registration.instanceContainer ||\n processedContainerUrls.has(registration.instanceContainer)\n ) {\n return null;\n }\n\n processedContainerUrls.add(registration.instanceContainer);\n\n return { registration, registeredModel };\n })\n .filter((match) => !!match);\n\n // Removed nested registrations.\n const containerUrls = registrations.map(({ registration }) => registration.instanceContainer);\n\n return registrations.filter(({ registration }) => {\n return !containerUrls.some(\n (containerUrl) =>\n containerUrl &&\n containerUrl !== registration.instanceContainer &&\n registration.instanceContainer?.startsWith(containerUrl),\n );\n });\n }\n\n private async updateTypeRegistrations(remoteModel: SolidModel): Promise<void> {\n if (!isRegisteredModel(remoteModel)) {\n return;\n }\n\n const container = isContainer(remoteModel) ? remoteModel : createRemoteContainer(remoteModel, this.localModels);\n const registeredChildren = isContainer(remoteModel)\n ? getContainerRegisteredClasses(remoteModel.static())\n : [remoteModel.static()];\n\n if (registeredChildren.length === 0) {\n return;\n }\n\n const typeIndex = await this.loadTypeIndex({ create: true });\n\n if (\n typeIndex.registrations.some(\n (registration) =>\n registration.instanceContainer && remoteModel.url.startsWith(registration.instanceContainer),\n )\n ) {\n return;\n }\n\n await container.register(typeIndex, registeredChildren);\n }\n\n private async loadChildren(model: SolidModel, childStatus?: JobStatus): Promise<void> {\n this.assertNotCancelled();\n\n if (!isContainer(model)) {\n return;\n }\n\n const children = await this.loadContainedModels(model, {\n status: childStatus,\n updateProgress: (update) => this.updateProgress(update),\n onDocumentError: (error) => this.handleDocumentError(error),\n onDocumentRead: (document) => {\n if (document.url.endsWith('/') || !document.updatedAt || document.url in this.documentsModifiedAt) {\n return;\n }\n\n this.documentsModifiedAt[document.url] = document.updatedAt;\n },\n onDocumentLoaded: async () => {\n this.assertNotCancelled();\n\n await this.updateProgress();\n },\n onDocumentIgnored: async (document) => {\n if (!document.updatedAt) {\n return;\n }\n\n await Cloud.getDocumentsCache().remember(\n requireUrlParentDirectory(document.url),\n document.url,\n document.updatedAt,\n );\n },\n });\n\n for (let index = 0; index < children.length; index++) {\n const child = children[index] as SolidModel;\n\n if (child instanceof Tombstone) {\n this.tombstones.add(child);\n\n continue;\n }\n\n if (this.tombstones.hasKey(child.url)) {\n await this.deleteChild(model, child);\n\n continue;\n }\n\n await this.loadChildren(child, childStatus?.children?.[index]);\n\n if (childStatus?.children?.[index]) {\n await this.updateProgress(() => (required(childStatus.children?.[index]).completed = true));\n }\n }\n }\n\n private async deleteChild(model: SolidModel, child: SolidModel): Promise<void> {\n for (const relation of model.static('relations')) {\n const relationInstance = model.requireRelation(relation);\n\n if (!relationInstance.related) {\n continue;\n }\n\n if (Array.isArray(relationInstance.related)) {\n relationInstance.related = relationInstance.related.filter((relatedModel) => relatedModel !== child);\n\n continue;\n }\n\n if (relationInstance.related === child) {\n relationInstance.related = null;\n\n continue;\n }\n }\n\n await child.forceDelete();\n }\n\n private async saveModelAndRelated(\n model: SolidModel,\n status?: JobStatus,\n processedModels?: Set<SolidModel>,\n ): Promise<void> {\n this.assertNotCancelled();\n processedModels ??= new Set();\n\n if (processedModels.has(model)) {\n return;\n }\n\n processedModels.add(model);\n\n if (isRemoteModel(model) && model.isSoftDeleted()) {\n model.enableHistory();\n model.enableTombstone();\n\n await model.forceDelete();\n\n return;\n }\n\n if (model.getDocumentUrl() && this.documentsWithErrors.has(model.requireDocumentUrl())) {\n return;\n }\n\n const wasDirty = model.isDirty();\n\n await model.save();\n\n if (wasDirty || isRemoteModel(model)) {\n this.syncedModelUrls.add(model.url);\n }\n\n if (isRemoteModel(model)) {\n const documentUrl = model.requireDocumentUrl();\n const modifiedAt = this.documentsModifiedAt[documentUrl];\n\n if (modifiedAt) {\n await Cloud.getDocumentsCache().remember(\n requireUrlParentDirectory(documentUrl),\n documentUrl,\n modifiedAt,\n );\n\n delete this.documentsModifiedAt[documentUrl];\n }\n }\n\n const children = arrayWithout(getRelatedAppModels(model), model);\n const childrenStatuses = status ? children.map(() => ({ completed: false })) : [];\n\n if (status) {\n status.children = childrenStatuses;\n }\n\n for (let index = 0; index < children.length; index++) {\n const child = children[index] as SolidModel;\n const childStatus = childrenStatuses[index];\n\n await this.saveModelAndRelated(child, childStatus, processedModels);\n\n if (childStatus) {\n await this.updateProgress(() => (childStatus.completed = true));\n }\n }\n }\n\n private async synchronizeModels(remoteModels: ObjectsMap<SolidModel>): Promise<SolidModel[]> {\n const synchronizedModelUrls = new Set<string>();\n const deletedModels = new Set<SolidModel>();\n\n for (const remoteModel of remoteModels.items()) {\n if (remoteModel instanceof Tombstone) {\n const localModel = this.localModels.get(remoteModel.resourceUrl);\n\n if (localModel) {\n await localModel.forceDelete();\n\n deletedModels.add(localModel);\n }\n\n continue;\n }\n\n const localModel = getLocalModel(remoteModel, this.localModels);\n\n if (!localModel.exists()) {\n this.syncedModelUrls.add(localModel.url);\n }\n\n await this.loadChildren(localModel);\n await SolidModel.synchronize(localModel, remoteModel, {\n constructors: getCloneConstructors(localModel),\n });\n await this.reconcileInconsistencies(localModel, remoteModel);\n await this.saveModelAndRelated(localModel);\n await this.addLocalModel(localModel);\n\n if (!this.rootLocalModels.includes(localModel)) {\n this.rootLocalModels.push(localModel);\n }\n\n synchronizedModelUrls.add(localModel.url);\n }\n\n for (const localModel of this.rootLocalModels) {\n if (deletedModels.has(localModel) || synchronizedModelUrls.has(localModel.url)) {\n continue;\n }\n\n await this.loadChildren(localModel);\n\n const remoteModel = getRemoteModel(localModel, remoteModels);\n\n await SolidModel.synchronize(localModel, remoteModel, {\n constructors: getCloneConstructors(localModel),\n });\n\n remoteModels.add(remoteModel);\n }\n\n const dirtyRemoteModels = [];\n\n for (const remoteModel of remoteModels.getItems()) {\n if (isDirtyOrHasDirtyChildren(remoteModel)) {\n dirtyRemoteModels.push(remoteModel);\n\n continue;\n }\n\n await this.rememberModelDocuments(remoteModel);\n }\n\n return dirtyRemoteModels;\n }\n\n private async reconcileInconsistencies(\n localModel: SolidModel,\n remoteModel: SolidModel,\n processedModels?: Set<SolidModel>,\n ): Promise<void> {\n localModel.rebuildAttributesFromHistory();\n localModel.setAttributes(remoteModel.getAttributes(true));\n\n processedModels ??= new Set();\n processedModels.add(localModel);\n\n for (const relation of getContainerRelations(localModel.static())) {\n await this.synchronizeContainerDocuments(\n localModel.requireRelation<SolidContainsRelation>(relation),\n remoteModel.requireRelation<SolidContainsRelation>(relation),\n );\n }\n\n const remoteRelatedModels = map(getRelatedAppModels(remoteModel), 'url');\n\n for (const localRelatedModel of getRelatedAppModels(localModel)) {\n if (\n processedModels.has(localRelatedModel) ||\n !localRelatedModel.isRelationLoaded('operations') ||\n !remoteRelatedModels.hasKey(localRelatedModel.url)\n ) {\n continue;\n }\n\n await this.reconcileInconsistencies(\n localRelatedModel,\n remoteRelatedModels.require(localRelatedModel.url),\n processedModels,\n );\n }\n\n if (localModel.isDirty()) {\n await SolidModel.synchronize(localModel, remoteModel, {\n constructors: getCloneConstructors(localModel),\n });\n }\n }\n\n private async synchronizeContainerDocuments(\n localRelation: SolidContainsRelation,\n remoteRelation: SolidContainsRelation,\n ): Promise<void> {\n const localModels = map(localRelation.related ?? [], 'url');\n const remoteModels = map(remoteRelation.related ?? [], 'url');\n const newLocalModelUrls = localModels\n .getKeys()\n .filter((url) => !remoteModels.hasKey(url) && !remoteModels.hasKey(encodeURI(url)));\n const newRemoteModelUrls = remoteModels\n .getKeys()\n .filter((url) => !localModels.hasKey(url) && !localModels.hasKey(encodeURI(url)));\n\n for (const url of newLocalModelUrls) {\n const localModel = localModels.require(url);\n const remoteModel = cloneLocalModel(localModel);\n\n remoteRelation.addRelated(remoteModel);\n remoteModels.add(remoteModel);\n }\n\n for (const url of newRemoteModelUrls) {\n const remoteModel = remoteModels.require(url);\n const localModel = cloneRemoteModel(remoteModel);\n\n localRelation.addRelated(localModel);\n localModels.add(localModel);\n this.syncedModelUrls.add(localModel.url);\n }\n\n for (const localModel of localModels.items()) {\n const remoteModel = remoteModels.require(localModel.url);\n\n await SolidModel.synchronize(localModel, remoteModel, {\n constructors: getCloneConstructors(localModel),\n });\n await this.saveModelAndRelated(localModel);\n }\n }\n\n private async rememberModelDocuments(model: SolidModel): Promise<void> {\n this.syncedModelUrls.add(model.url);\n\n if (!isContainer(model)) {\n const documentUrl = model.requireDocumentUrl();\n const modifiedAt = this.documentsModifiedAt[documentUrl];\n\n if (modifiedAt) {\n await Cloud.getDocumentsCache().remember(\n requireUrlParentDirectory(documentUrl),\n documentUrl,\n modifiedAt,\n );\n\n delete this.documentsModifiedAt[documentUrl];\n }\n\n return;\n }\n\n const children = getContainerRelations(model.static())\n .map((relation) => model.getRelationModels(relation) ?? [])\n .flat();\n\n for (const child of children) {\n await this.rememberModelDocuments(child);\n }\n }\n\n private async ignoringDocumentErrors(operation: Function): Promise<void> {\n try {\n await operation();\n } catch (error) {\n this.handleDocumentError(error);\n }\n }\n\n private handleDocumentError(error: unknown): void {\n if (isInstanceOf(error, MalformedSolidDocumentError)) {\n // eslint-disable-next-line no-console\n console.warn(error.message);\n\n error.documentUrl && this.documentsWithErrors.add(error.documentUrl);\n\n return;\n }\n\n if (isInstanceOf(error, InvalidModelAttributes)) {\n // eslint-disable-next-line no-console\n console.warn(error.message);\n\n const primaryKey = error.attributes[requireBootedModel(error.modelName).primaryKey];\n const documentUrl = primaryKey && urlRoute(toString(primaryKey));\n\n documentUrl && this.documentsWithErrors.add(documentUrl);\n\n return;\n }\n\n throw error;\n }\n\n}\n","import { defineServiceState, replaceExisting, translateWithDefault } from '@aerogel/core';\nimport { Solid } from '@aerogel/plugin-solid';\nimport type { ErrorSource } from '@aerogel/core';\nimport type { Nullable } from '@noeldemartin/utils';\nimport type { SolidModelConstructor, SolidSchemaDefinition } from 'soukai-solid';\n\nimport Migrate from '@aerogel/plugin-local-first/jobs/Migrate';\nimport type Sync from '@aerogel/plugin-local-first/jobs/Sync';\n\nexport const CloudStatus = {\n Disconnected: 'disconnected',\n Offline: 'offline',\n Online: 'online',\n Syncing: 'syncing',\n Migrating: 'migrating',\n} as const;\n\nexport interface ModelRegistration {\n modelClass: SolidModelConstructor;\n path?: string;\n}\n\nexport type TCloudStatus = (typeof CloudStatus)[keyof typeof CloudStatus];\n\nexport const DEFAULT_STATE = { manualSetup: false };\n\nexport default defineServiceState({\n name: 'cloud',\n persist: [\n 'localModelUpdates',\n 'migrationDismissed',\n 'migrationJob',\n 'modelCollections',\n 'rootModelCollections',\n 'pollingEnabled',\n 'pollingMinutes',\n 'ready',\n 'startupSync',\n ],\n initialState: () => ({\n autoPush: true,\n localModelUpdates: {} as Record<string, number>,\n migrationDismissed: false,\n migrationJob: null as Nullable<Migrate>,\n migrationPostponed: false,\n modelCollections: {} as Record<string, string[]>,\n rootModelCollections: {} as Record<string, string>,\n pollingEnabled: true,\n pollingMinutes: 10,\n ready: false,\n manualSetup: DEFAULT_STATE.manualSetup,\n registeredModels: [] as ModelRegistration[],\n schemaMigrations: new Map<SolidModelConstructor, SolidModelConstructor | SolidSchemaDefinition>(),\n setupDismissed: false,\n setupOngoing: false,\n startupSync: true,\n status: CloudStatus.Disconnected as TCloudStatus,\n syncError: null as Nullable<ErrorSource>,\n syncJob: null as Nullable<Sync>,\n }),\n serialize: (state) => replaceExisting(state, { migrationJob: state.migrationJob?.serialize() }),\n restore: (state) =>\n replaceExisting(state, {\n migrationJob: state.migrationJob && Migrate.restore(state.migrationJob),\n }),\n watch: {\n migrationJob(migrationJob) {\n migrationJob?.listeners.add({ onUpdated: () => this.updatePersistedState('migrationJob') });\n },\n },\n computed: {\n disconnected: ({ status }) => status === CloudStatus.Disconnected,\n online: ({ status }) => status === CloudStatus.Online,\n offline: ({ status }) => status === CloudStatus.Offline,\n syncing: ({ status }) => status === CloudStatus.Syncing,\n migrating: ({ status }) => status === CloudStatus.Migrating,\n localChanges({ localModelUpdates }) {\n return Object.values(localModelUpdates).reduce((total, count) => total + count, 0);\n },\n dirty(): boolean {\n return this.localChanges > 0;\n },\n migrationStarted({ migrationJob }): boolean {\n return !!migrationJob;\n },\n migrationDisabledReason({ status, ready }): string | null {\n if (!Solid.isLoggedIn()) {\n return translateWithDefault(\n 'cloud.migrationNotLoggedIn',\n 'You need to reconnect before starting the migration',\n );\n }\n\n if (!ready) {\n return translateWithDefault(\n 'cloud.migrationNotReady',\n 'You need to backup your data before starting the migration',\n );\n }\n\n if (status === CloudStatus.Syncing || status === CloudStatus.Migrating) {\n return translateWithDefault(\n 'cloud.migrationNotSyncing',\n 'Wait for syncing to finish before starting the migration',\n );\n }\n\n if (!this.online) {\n return translateWithDefault(\n 'cloud.migrationNotOnline',\n 'You need to be online in order to start the migration',\n );\n }\n\n return null;\n },\n },\n});\n","import {\n Semaphore,\n after,\n facade,\n fail,\n getLocationQueryParameter,\n hasLocationQueryParameter,\n isArray,\n isTesting,\n parseBoolean,\n} from '@noeldemartin/utils';\nimport { Errors, Events, appNamespace, dispatch, translateWithDefault } from '@aerogel/core';\nimport { Solid } from '@aerogel/plugin-solid';\nimport {\n DocumentsCache,\n SolidContainer,\n SolidModel,\n Tombstone,\n isContainer,\n isContainerClass,\n isSolidModel,\n} from 'soukai-solid';\nimport { getTrackedModels, trackModels, trackModelsCollection } from '@aerogel/plugin-soukai';\nimport { watchEffect } from 'vue';\nimport { getBootedModels, requireEngine } from 'soukai';\nimport type { Authenticator } from '@aerogel/plugin-solid';\nimport type { Engine } from 'soukai';\nimport type { JobListener } from '@aerogel/core';\nimport type { SolidContainsRelation, SolidModelConstructor, SolidSchemaDefinition } from 'soukai-solid';\n\nimport {\n clearLocalModelUpdates,\n createRemoteModel,\n getLocalModels,\n getRemoteClass,\n getRemoteContainersCollection,\n updateRemoteModel,\n} from '@aerogel/plugin-local-first/lib/mirroring';\nimport Backup from '@aerogel/plugin-local-first/jobs/Backup';\nimport Migrate from '@aerogel/plugin-local-first/jobs/Migrate';\nimport Sync from '@aerogel/plugin-local-first/jobs/Sync';\nimport SyncQueue from '@aerogel/plugin-local-first/lib/SyncQueue';\nimport {\n getContainedModels,\n getContainerRelations,\n getRelatedClasses,\n} from '@aerogel/plugin-local-first/lib/inference';\n\nimport Service, { CloudStatus } from './Cloud.state';\n\nexport interface RegisterOptions {\n path?: string;\n}\n\nexport interface SyncOptions extends JobListener {\n model?: SolidModel;\n models?: SolidModel[];\n refreshUserProfile?: boolean;\n syncDirty?: boolean;\n}\n\nexport class CloudService extends Service {\n\n protected asyncLock: Semaphore = new Semaphore();\n protected engine: Engine | null = null;\n protected pollingInterval: NodeJS.Timeout | null = null;\n protected documentsCache: DocumentsCache | null = null;\n\n public async whenReady<T>(callback: () => T): Promise<T> {\n if (this.ready) {\n return callback();\n }\n\n return new Promise((resolve) => {\n const onReady = () => resolve(callback());\n\n Events.once('cloud:ready', onReady);\n });\n }\n\n public async setup(modelUrlMappings?: WeakMap<SolidModelConstructor, Record<string, string>>): Promise<void> {\n this.setupOngoing = true;\n\n try {\n await this.backup(modelUrlMappings);\n await this.setReady(true);\n await this.sync();\n } finally {\n this.setupOngoing = false;\n }\n }\n\n public getEngine(): Engine | null {\n return this.engine;\n }\n\n public requireEngine(): Engine {\n return this.engine ?? fail('Could not get required Engine');\n }\n\n public dismissSetup(): void {\n this.setupDismissed = true;\n }\n\n public dismissMigration(): void {\n this.migrationDismissed = true;\n }\n\n public postponeMigration(): void {\n this.migrationPostponed = true;\n }\n\n public async syncIfOnline(options?: SyncOptions): Promise<void>;\n public async syncIfOnline(model: SolidModel): Promise<void>;\n public async syncIfOnline(models: SolidModel[]): Promise<void>;\n public async syncIfOnline(config: SyncOptions | SolidModel | SolidModel[] = {}): Promise<void> {\n if (!this.online) {\n return;\n }\n\n await this.sync(config as SyncOptions);\n }\n\n public async sync(options?: SyncOptions): Promise<void>;\n public async sync(model: SolidModel): Promise<void>;\n public async sync(models: SolidModel[]): Promise<void>;\n public async sync(config: SyncOptions | SolidModel | SolidModel[] = {}): Promise<void> {\n const options = isArray(config)\n ? { models: config }\n : config instanceof SolidModel\n ? { model: config }\n : config;\n\n if (!Solid.isLoggedIn() || !this.ready || !this.online) {\n return;\n }\n\n await this.asyncLock.run(async () => {\n let models = options.model ? [options.model] : options.models;\n const start = Date.now();\n\n this.syncError = null;\n this.status = CloudStatus.Syncing;\n\n SyncQueue.clear(models);\n\n try {\n await Events.emit('cloud:sync-started', models);\n\n if (options.refreshUserProfile) {\n await Solid.refreshUserProfile();\n }\n\n const syncDirty = options.syncDirty ?? true;\n let syncs = 0;\n\n do {\n this.syncJob = new Sync(models);\n\n this.syncJob.listeners.add(options);\n\n await dispatch(this.syncJob);\n\n if (this.syncJob.cancelled) {\n return;\n }\n\n syncs++;\n models = this.getDirtyLocalModels().filter(\n (model) => !this.syncJob?.documentsWithErrors.has(model.requireDocumentUrl()),\n );\n } while (syncDirty && models.length > 0 && syncs < 3);\n\n if (!isTesting('unit')) {\n await after({ milliseconds: Math.max(500, 1000 - (Date.now() - start)) });\n }\n\n this.syncJob = null;\n } catch (error) {\n if (isTesting()) {\n throw error;\n }\n\n this.syncJob = null;\n this.syncError = error;\n\n await Errors.report(error, translateWithDefault('cloud.syncFailed', 'Sync failed'));\n } finally {\n this.status = CloudStatus.Online;\n\n await Events.emit('cloud:sync-completed', models);\n }\n });\n }\n\n public shouldMigrate(): boolean {\n return this.schemaMigrations.size > 0;\n }\n\n public async migrate(listener?: JobListener): Promise<void> {\n if (!this.online || !Solid.isLoggedIn() || !this.ready) {\n throw new Error('Data cannot be migrated at the moment');\n }\n\n if (!this.shouldMigrate()) {\n return;\n }\n\n await this.asyncLock.run(async () => {\n this.status = CloudStatus.Migrating;\n this.migrationJob ??= new Migrate();\n\n const start = Date.now();\n const removeListeners: Function[] = [];\n const models = (this.migrationJob.models ??= getLocalModels());\n\n SyncQueue.clear(models);\n\n try {\n listener && removeListeners.push(this.migrationJob.listeners.add(listener));\n\n await Events.emit('cloud:migration-started', models);\n await dispatch(this.migrationJob);\n\n if (this.migrationJob.cancelled) {\n await Events.emit('cloud:migration-cancelled', models);\n\n return;\n }\n\n this.migrationJob = null;\n this.migrationDismissed = false;\n this.migrationPostponed = false;\n\n await after({ milliseconds: Math.max(0, 1000 - (Date.now() - start)) });\n await Events.emit('cloud:migration-completed', models);\n } catch (error) {\n await Errors.report(error, translateWithDefault('cloud.migrationFailed', 'Migration failed'));\n } finally {\n this.status = CloudStatus.Online;\n\n removeListeners.forEach((removeListener) => removeListener?.());\n }\n });\n }\n\n public async register(modelClass: SolidModelConstructor, options: RegisterOptions = {}): Promise<void> {\n if (this.registeredModels.find((registered) => modelClass === registered.modelClass)) {\n return;\n }\n\n const engine = this.engine;\n\n if (engine) {\n getRelatedClasses(modelClass).forEach((relatedClass) => getRemoteClass(relatedClass).setEngine(engine));\n }\n\n this.whenReady(async () => {\n const rootCollection = this.rootModelCollections[modelClass.modelName];\n\n modelClass.useSoftDeletes(true);\n\n await modelClass.exclusive(\n async () =>\n (modelClass.collection = rootCollection ?? getRemoteContainersCollection(modelClass, options.path)),\n );\n });\n\n await trackModels(modelClass, {\n created: (model) => this.ready && createRemoteModel(model),\n updated: (model) => this.ready && updateRemoteModel(model),\n deleted: (model) =>\n this.ready && clearLocalModelUpdates(new Set([model.url ?? model.getDeletedPrimaryKey()])),\n });\n\n if (isContainerClass(modelClass)) {\n getContainerRelations(modelClass).forEach((relation) => {\n const relatedClass = modelClass\n .instance()\n .requireRelation<SolidContainsRelation>(relation).relatedClass;\n\n relatedClass.on('created', (model) => this.ready && createRemoteModel(model));\n relatedClass.on('updated', (model) => this.ready && updateRemoteModel(model));\n relatedClass.on(\n 'deleted',\n (model) =>\n this.ready && clearLocalModelUpdates(new Set([model.url ?? model.getDeletedPrimaryKey()])),\n );\n });\n }\n\n this.registeredModels.push({ modelClass, path: options.path });\n\n for (const collection of this.modelCollections[modelClass.modelName] ?? []) {\n await trackModelsCollection(modelClass, collection);\n }\n }\n\n public registerSchemaMigration(\n modelClass: SolidModelConstructor,\n schema: SolidModelConstructor | SolidSchemaDefinition,\n ): void {\n this.schemaMigrations.set(modelClass, schema);\n }\n\n public requireRemoteCollection(modelClass: SolidModelConstructor): string {\n for (const registration of this.registeredModels) {\n if (modelClass !== registration.modelClass) {\n continue;\n }\n\n return getRemoteContainersCollection(registration.modelClass, registration.path);\n }\n\n throw new Error(`Failed resolving remote collection for '${modelClass.modelName}' model`);\n }\n\n public getDocumentsCache(): DocumentsCache {\n if (!this.documentsCache) {\n this.documentsCache = new DocumentsCache(appNamespace(), requireEngine());\n }\n\n return this.documentsCache;\n }\n\n protected override async boot(): Promise<void> {\n await Solid.booted;\n\n Solid.isLoggedIn() && this.login(Solid.authenticator);\n\n Events.on('auth:login', ({ authenticator }) => this.login(authenticator));\n Events.on('auth:logout', () => this.logout());\n Events.on('purge-storage', () => this.getDocumentsCache().clear());\n Events.once('application-ready', () => this.onApplicationReady());\n Events.once('application-mounted', () => this.onApplicationMounted());\n\n watchEffect(() => {\n this.pollingInterval && clearInterval(this.pollingInterval);\n\n if (!this.pollingEnabled || this.migrationJob) {\n this.pollingInterval = null;\n\n return;\n }\n\n this.pollingInterval = setInterval(() => this.sync(), this.pollingMinutes * 60 * 1000);\n });\n\n this.watchNetworkStatus();\n await this.bustDocumentsCache();\n await this.registerModels();\n }\n\n protected getDirtyLocalModels(): SolidModel[] {\n const urls = Object.keys(this.localModelUpdates);\n const dirtyLocalModels = [];\n\n for (const { modelClass } of this.registeredModels) {\n for (const model of getTrackedModels(modelClass, { includeSoftDeleted: true })) {\n dirtyLocalModels.push(...this.getModelsIn(urls, model));\n }\n }\n\n return dirtyLocalModels;\n }\n\n protected getModelsIn(urls: string[], model: SolidModel): SolidModel[] {\n const models = [];\n\n if (urls.includes(model.url)) {\n models.push(model);\n }\n\n if (isContainer(model)) {\n models.push(\n ...getContainedModels(model)\n .map((containedModel) => this.getModelsIn(urls, containedModel))\n .flat(),\n );\n }\n\n return models;\n }\n\n protected async setReady(ready: boolean): Promise<void> {\n if (this.ready || !ready) {\n return;\n }\n\n await Events.emit('cloud:ready');\n\n this.ready = true;\n }\n\n protected async backup(modelUrlMappings?: WeakMap<SolidModelConstructor, Record<string, string>>): Promise<void> {\n await Events.emit('cloud:backup-started');\n\n modelUrlMappings ??= new WeakMap();\n\n const job = new Backup();\n\n for (const { modelClass, path } of this.registeredModels) {\n for (const [local, remote] of Object.entries(modelUrlMappings.get(modelClass) ?? {})) {\n job.migrateUrl(modelClass, local, remote);\n }\n\n const localCollection = modelClass.instance().getDefaultCollection();\n const remoteCollection = getRemoteContainersCollection(modelClass, path);\n\n await modelClass.exclusive(async () => (modelClass.collection = remoteCollection));\n\n job.migrateCollection(modelClass, localCollection, remoteCollection);\n }\n\n await dispatch(job);\n await Events.emit('cloud:backup-completed');\n }\n\n protected async onApplicationReady(): Promise<void> {\n if (this.ready || !Solid.isLoggedIn()) {\n return;\n }\n\n await this.setReady(!getLocalModels().some((model) => model.url.startsWith('solid://')));\n }\n\n protected async onApplicationMounted(): Promise<void> {\n if (Solid.isLoggedIn() && !this.ready && !this.manualSetup) {\n await this.setup();\n\n return;\n }\n\n if (!this.syncOnStartup()) {\n return;\n }\n\n await this.sync();\n }\n\n protected login(authenticator: Authenticator): void {\n const relatedClasses = [...this.registeredModels]\n .map(({ modelClass }) => getRelatedClasses(modelClass))\n .flat()\n .concat([Tombstone]);\n\n this.status = CloudStatus.Online;\n this.engine = authenticator.engine;\n\n getRemoteClass(SolidContainer).setEngine(this.engine);\n\n for (const relatedClass of relatedClasses) {\n getRemoteClass(relatedClass).setEngine(this.engine);\n }\n }\n\n protected async logout(): Promise<void> {\n this.setState({\n autoPush: true,\n localModelUpdates: {},\n migrationDismissed: false,\n migrationJob: null,\n migrationPostponed: false,\n modelCollections: {},\n rootModelCollections: {},\n pollingEnabled: true,\n pollingMinutes: 10,\n ready: false,\n schemaMigrations: new Map(),\n setupDismissed: false,\n setupOngoing: false,\n startupSync: true,\n status: CloudStatus.Disconnected,\n syncError: null,\n syncJob: null,\n });\n\n await this.getDocumentsCache().clear();\n }\n\n private watchNetworkStatus(): void {\n globalThis.addEventListener('online', () => {\n if (this.status !== CloudStatus.Offline) {\n return;\n }\n\n this.status = CloudStatus.Online;\n });\n\n globalThis.addEventListener('offline', () => {\n if (this.status !== CloudStatus.Online) {\n return;\n }\n\n this.status = CloudStatus.Offline;\n });\n }\n\n private syncOnStartup(): boolean {\n if (hasLocationQueryParameter('startupSync')) {\n return parseBoolean(getLocationQueryParameter('startupSync'));\n }\n\n if (this.migrationJob) {\n return false;\n }\n\n return this.startupSync;\n }\n\n private async bustDocumentsCache(): Promise<void> {\n if (\n !hasLocationQueryParameter('bustDocumentsCache') ||\n !parseBoolean(getLocationQueryParameter('bustDocumentsCache'))\n ) {\n return;\n }\n\n await this.getDocumentsCache().clear();\n }\n\n private async registerModels(): Promise<void> {\n const models = getBootedModels();\n\n for (const model of models.values()) {\n if (!isSolidModel(model) || !model.cloud) {\n continue;\n }\n\n await this.register(model, typeof model.cloud === 'boolean' ? {} : model.cloud);\n }\n }\n\n}\n\nexport default facade(CloudService);\n\ndeclare module '@aerogel/core' {\n export interface EventsPayload {\n 'cloud:ready': void;\n 'cloud:backup-started': void;\n 'cloud:backup-completed': void;\n 'cloud:migration-started': SolidModel[];\n 'cloud:migration-cancelled': SolidModel[];\n 'cloud:migration-completed': SolidModel[];\n 'cloud:sync-started': SolidModel[] | undefined;\n 'cloud:sync-completed': SolidModel[] | undefined;\n }\n}\n\ndeclare module 'soukai-solid' {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n namespace SolidModel {\n export const cloud: boolean | RegisterOptions | undefined;\n }\n}\n","<template>\n <Modal :title=\"$td('cloud.logIn.title', 'Connect account')\">\n <Markdown\n lang-key=\"cloud.logIn.info\"\n lang-default=\"Log in to your [Solid account](https://solidproject.org) to keep data safe across devices.\"\n />\n <Link\n class=\"text-sm\"\n @click=\"\n $ui.alert(\n $td('cloud.logIn.learnMore', 'What is Solid?'),\n $td(\n 'cloud.logIn.learnMoreMessage',\n 'Solid is a decentralized storage protocol built on top of web standards. ' +\n 'If you want to use this app across devices, ' +\n 'you can use Solid to keep changes in sync. ' +\n 'Even if you use it in a single device, ' +\n 'this will also keep your data secure in case your device is lost.\\n\\n' +\n 'In any case, Focus works 100% offline and you can connect your Solid POD later on. ' +\n 'If you\\'ve never heard of Solid and you\\'re just trying things out, ' +\n 'you can keep using it without an account.\\n\\n' +\n '[Learn more](https://solidproject.org)'\n )\n )\n \"\n >\n {{ $td('cloud.logIn.learnMore', 'What is Solid?') }}\n </Link>\n <SolidLogin no-loading class=\"mt-4\" />\n </Modal>\n</template>\n\n<script setup lang=\"ts\">\nimport { Link, Markdown, Modal } from '@aerogel/core';\nimport { SolidLogin } from '@aerogel/plugin-solid';\n</script>\n","<template>\n <details v-if=\"!$solid.hasLoggedIn()\" class=\"mt-4\">\n <summary>\n <span class=\"text-base font-semibold\">{{ $td('settings.dangerZone', 'Danger zone') }}</span>\n </summary>\n <Button variant=\"danger\" class=\"mt-4\" @click=\"purgeData()\">\n <IconTrash class=\"size-4\" />\n <span class=\"ml-1\">{{ $td('settings.purge', 'Purge data') }}</span>\n </Button>\n </details>\n</template>\n\n<script setup lang=\"ts\">\nimport IconTrash from '~icons/zondicons/trash';\n\nimport { Button, Storage, UI, translateWithDefault } from '@aerogel/core';\n\nimport AccountLoginModal from '@aerogel/plugin-local-first/components/AccountLoginModal.vue';\n\nasync function purgeData(): Promise<void> {\n const confirmed = await UI.confirm(\n translateWithDefault('settings.purgeConfirmTitle', 'Delete everything?'),\n translateWithDefault(\n 'settings.purgeConfirmMessage',\n 'If you proceed, all your data will be deleted forever. ' +\n 'If you want to save it before wiping this device, ' +\n 'you can [connect to your Solid account](#action:connect) first.',\n ),\n {\n acceptVariant: 'danger',\n acceptText: translateWithDefault('settings.purgeConfirmAccept', 'Purge data'),\n actions: { connect: () => UI.modal(AccountLoginModal) },\n },\n );\n\n if (!confirmed) {\n return;\n }\n\n await UI.closeAllModals();\n await Storage.purge();\n}\n</script>\n","import { defineSettings } from '@aerogel/core';\n\nimport PurgeData from './PurgeData.vue';\n\nexport default defineSettings([\n {\n priority: 0,\n component: PurgeData,\n },\n]);\n","<template>\n <Modal title-hidden close-hidden :title=\"$td('account.title', 'Account')\">\n <div class=\"relative flex items-center rounded-md bg-gray-100 p-4 pr-12\">\n <SolidAvatar class=\"mr-2 size-16 shrink-0\" />\n <div class=\"flex flex-col overflow-hidden\">\n <span class=\"font-semibold\">{{ $solid.user?.name ?? $td('user.anonymous', 'Anonymous') }}</span>\n <Link :href=\"$solid.user?.webId\" class=\"mt-0.5 truncate text-sm font-light text-gray-500\">\n {{ $solid.user?.webId }}\n </Link>\n </div>\n <Button\n size=\"icon\"\n variant=\"ghost\"\n class=\"absolute top-1 right-1 hover:bg-gray-200\"\n :aria-label=\"$td('user.settings', 'Settings')\"\n :title=\"$td('user.settings', 'Settings')\"\n @click=\"$ui.modal(SettingsModal)\"\n >\n <IconCog class=\"size-5\" />\n </Button>\n </div>\n\n <div class=\"px-2\">\n <div v-if=\"$cloud.syncing\" class=\"mt-4 flex items-center gap-2\">\n <IconRefresh class=\"mt-0.5 size-6 shrink-0 animate-spin self-start text-green-500\" />\n <div class=\"flex w-full flex-col\">\n <Markdown lang-key=\"cloud.info.syncing\" lang-default=\"Synchronizing...\" />\n <ProgressBar v-if=\"$cloud.syncJob\" :job=\"$cloud.syncJob\" filled-class=\"bg-green-500\" />\n </div>\n </div>\n <div v-else-if=\"$solid.loginOngoing\" class=\"mt-4 flex items-center gap-2\">\n <IconRefresh class=\"mt-0.5 size-6 shrink-0 animate-spin self-start text-green-500\" />\n <Markdown lang-key=\"cloud.info.reconnecting\" lang-default=\"Reconnecting...\" />\n </div>\n <div v-else-if=\"error\" class=\"mt-4 flex items-center gap-2\">\n <IconWarning class=\"mt-0.5 size-6 shrink-0 self-start text-red-500\" />\n <div>\n <Markdown :text=\"errorDescription\" />\n <Link\n v-if=\"showErrorDetails\"\n class=\"text-sm text-red-700 opacity-50 hover:opacity-75 focus-visible:opacity-75\"\n @click=\"$errors.inspect(error)\"\n >\n {{ $td('errors.viewDetails', 'View details') }}\n </Link>\n </div>\n </div>\n <div v-else-if=\"!$cloud.ready\" class=\"mt-4 flex items-center gap-2\">\n <IconWarning class=\"mt-0.5 size-6 shrink-0 self-start text-yellow-500\" />\n <Markdown lang-key=\"cloud.info.setup\" lang-default=\"Your data is not backed up yet.\" />\n </div>\n <div v-else-if=\"$cloud.dirty\" class=\"mt-4 flex items-center gap-2\">\n <IconWarning class=\"mt-0.5 size-6 shrink-0 self-start text-yellow-500\" />\n <Markdown\n lang-key=\"cloud.info.changes\"\n lang-default=\"Everything is up to date. | There is one local change. | There are {n} local changes.\"\n :lang-params=\"$cloud.localChanges\"\n />\n </div>\n <div v-else-if=\"$cloud.online || $cloud.offline\" class=\"mt-4 flex items-center gap-2\">\n <IconCheckmarkOutline\n class=\"mt-0.5 size-6 shrink-0 self-start\"\n :class=\"{ 'text-green-500': $cloud.online, 'text-gray-700': $cloud.offline }\"\n />\n <Markdown\n v-if=\"$cloud.online\"\n lang-key=\"cloud.info.changes\"\n lang-default=\"Everything is up to date.\"\n :lang-params=\"0\"\n />\n <Markdown\n v-else\n lang-key=\"cloud.info.offline\"\n lang-default=\"Everything is up to date, but you're currently offline.\"\n />\n </div>\n <div v-else class=\"mt-4 flex items-center gap-2\">\n <IconWarning class=\"mt-0.5 size-6 shrink-0 self-start text-yellow-500\" />\n <Markdown\n lang-key=\"cloud.info.disconnected\"\n lang-default=\"You are disconnected from your Solid account, all the changes you make will remain in your device.\"\n />\n </div>\n <AdvancedOptions class=\"mt-2\">\n <ul class=\"flex flex-col gap-2\">\n <li>\n <Checkbox\n v-model=\"$solid.autoReconnect\"\n label-class=\"text-base\"\n :label=\"$td('cloud.advanced.reconnect', 'Reconnect on startup')\"\n />\n </li>\n <li>\n <Checkbox\n v-model=\"$cloud.startupSync\"\n label-class=\"text-base\"\n :label=\"$td('cloud.advanced.startupSync', 'Synchronize on startup')\"\n />\n </li>\n <li>\n <Checkbox v-model=\"$cloud.pollingEnabled\" label-class=\"text-base\">\n <div class=\"flex items-center\">\n <span aria-hidden=\"true\">{{ pollingText[0] }}</span>\n <EditableContent\n type=\"number\"\n :text=\"`${$cloud.pollingMinutes}`\"\n :aria-label=\"\n $td('cloud.advanced.pollingMinutes', 'Synchronization interval (in minutes)')\n \"\n class=\"focus-within:border-primary-600 mx-1 -mb-px border-b\"\n @update=\"$cloud.pollingMinutes = $event as number\"\n >\n {{ $cloud.pollingMinutes }}\n </EditableContent>\n <span v-if=\"pollingText.length > 1\" aria-hidden=\"true\">{{ pollingText[1] }}</span>\n </div>\n </Checkbox>\n </li>\n </ul>\n </AdvancedOptions>\n </div>\n\n <div v-if=\"!$solid.loginOngoing\" class=\"mt-4 flex flex-row-reverse justify-start gap-2\">\n <Button\n v-if=\"$cloud.syncing\"\n variant=\"secondary\"\n :disabled=\"cancellingSync\"\n @click=\"cancelSync()\"\n >\n <IconStop class=\"size-5\" />\n <span>{{\n cancellingSync ? $td('cloud.stopping', 'Stopping...') : $td('cloud.stop', 'Stop synchronization')\n }}</span>\n </Button>\n <Button v-else-if=\"!$solid.isLoggedIn()\" @click=\"$solid.reconnect({ force: true })\">\n <IconRefresh class=\"size-5\" />\n <span>{{ $td('cloud.reconnect', 'Reconnect') }}</span>\n </Button>\n <Button\n v-else-if=\"$cloud.ready\"\n :disabled=\"$cloud.offline\"\n @click=\"$cloud.sync({ refreshUserProfile: true })\"\n >\n <IconRefresh class=\"size-5\" />\n <span>{{ $td('cloud.sync', 'Synchronize') }}</span>\n </Button>\n <Button v-else @click=\"(($cloud.setupDismissed = false), close(), $cloud.manualSetup || $cloud.setup())\">\n <IconCloudUpload class=\"size-5\" />\n <span>{{ $td('cloud.setup.submit', 'Back up now') }}</span>\n </Button>\n <Button v-if=\"!$cloud.syncing\" variant=\"secondary\" @click=\"$solid.logout()\">\n <IconLogout class=\"size-5\" />\n <span>{{ $cloud.ready ? $td('cloud.logOut', 'Log out') : $td('cloud.disconnect', 'Disconnect') }}</span>\n </Button>\n </div>\n </Modal>\n</template>\n\n<script setup lang=\"ts\">\nimport IconCheckmarkOutline from '~icons/zondicons/checkmark-outline';\nimport IconCloudUpload from '~icons/ic/sharp-cloud-upload';\nimport IconCog from '~icons/zondicons/cog';\nimport IconLogout from '~icons/material-symbols/logout-rounded';\nimport IconRefresh from '~icons/zondicons/refresh';\nimport IconStop from '~icons/ic/baseline-stop';\nimport IconWarning from '~icons/ion/warning';\n\nimport {\n AdvancedOptions,\n Button,\n Checkbox,\n EditableContent,\n Link,\n Markdown,\n Modal,\n ProgressBar,\n SettingsModal,\n translateWithDefault,\n useEvent,\n useModal,\n} from '@aerogel/core';\nimport { computed, ref } from 'vue';\nimport { Solid, SolidAvatar } from '@aerogel/plugin-solid';\n\nimport Cloud from '@aerogel/plugin-local-first/services/Cloud';\n\nconst { close } = useModal();\nconst cancellingSync = ref(false);\nconst pollingText = translateWithDefault('cloud.advanced.polling', 'Synchronize every {minutes} minutes', {\n minutes: '%%separator%%',\n}).split('%%separator%%');\nconst error = computed(() => Solid.error ?? Cloud.syncError);\nconst errorDescription = computed(() => {\n if (!error.value) {\n return;\n }\n\n if (typeof error.value === 'string') {\n return error.value;\n }\n\n return translateWithDefault('cloud.info.error', 'There has been an error connecting.');\n});\nconst showErrorDetails = computed(() => error.value && typeof error.value !== 'string');\n\nasync function cancelSync() {\n if (!Cloud.syncJob) {\n return;\n }\n\n cancellingSync.value = true;\n\n await Promise.race([Cloud.syncJob.cancel(), Cloud.syncJob.completed]);\n\n cancellingSync.value = false;\n}\n\nuseEvent('auth:logout', close);\n</script>\n","<template>\n <div class=\"relative size-12\">\n <button\n class=\"clickable focus-visible:outline-primary-600 flex size-full rounded-full focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2\"\n type=\"button\"\n :aria-label=\"$td('account.open', 'Open account')\"\n :title=\"$td('account.open', 'Open account')\"\n @click=\"$ui.modal(AccountModal)\"\n >\n <SolidAvatar class=\"size-full\" />\n <div\n v-if=\"accountStatus.loading\"\n class=\"absolute -inset-1 animate-spin rounded-full border-2 border-[currentColor_transparent] text-green-500\"\n />\n </button>\n <div\n class=\"pointer-events-none absolute right-0 bottom-0 size-3 rounded-full border-2 border-white\"\n :class=\"accountStatus.classes\"\n >\n <span class=\"sr-only\">{{ accountStatus.message }}</span>\n </div>\n </div>\n</template>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue';\nimport { Solid, SolidAvatar } from '@aerogel/plugin-solid';\nimport { translateWithDefault } from '@aerogel/core';\n\nimport Cloud from '@aerogel/plugin-local-first/services/Cloud';\nimport { CloudStatus } from '@aerogel/plugin-local-first/services/Cloud.state';\n\nimport AccountModal from './AccountModal.vue';\n\ninterface AccountStatus {\n classes: string;\n message: string;\n loading?: boolean;\n}\n\nconst accountStatus = computed((): AccountStatus => {\n if (Cloud.syncing || Solid.loginOngoing) {\n return {\n loading: true,\n classes: 'bg-green-500 sr-only',\n message: getAccountStatusMessage() ?? '',\n };\n }\n\n if (Solid.error || Cloud.syncError) {\n return {\n classes: 'bg-red-500',\n message: translateWithDefault('account.error', 'There has been an error connecting with your account.'),\n };\n }\n\n if (!Solid.isLoggedIn() || Cloud.dirty || !Cloud.ready) {\n return {\n classes: 'bg-yellow-500',\n message: translateWithDefault(\n 'account.dirty',\n 'There are local changes that haven\\'t been synchronized yet.',\n ),\n };\n }\n\n return {\n classes: Cloud.status === CloudStatus.Online ? 'bg-green-500' : 'bg-gray-500',\n message: getAccountStatusMessage() ?? '',\n };\n});\n\nfunction getAccountStatusMessage(): string | undefined {\n switch (Cloud.status) {\n case CloudStatus.Syncing:\n return translateWithDefault('cloud.status.syncing', 'Synchronization in progress');\n case CloudStatus.Migrating:\n return translateWithDefault('cloud.status.migrating', 'Migration in progress');\n case CloudStatus.Online:\n return translateWithDefault('cloud.status.online', 'Online');\n case CloudStatus.Offline:\n return translateWithDefault('cloud.status.offline', 'Offline');\n case CloudStatus.Disconnected:\n return translateWithDefault('cloud.status.disconnected', 'Disconnected');\n }\n}\n</script>\n","<template>\n <DropdownMenu\n align=\"start\"\n :options=\"[\n { label: $td('user.logIn', 'Connect account'), click: () => $ui.modal(AccountLoginModal) },\n { label: $td('user.settings', 'Settings'), click: () => $ui.modal(SettingsModal) },\n ]\"\n >\n <Button\n size=\"icon\"\n variant=\"ghost\"\n :aria-label=\"$td('user.menu', 'Configuration')\"\n :title=\"$td('user.menu', 'Configuration')\"\n >\n <IconCog class=\"size-5\" />\n </Button>\n </DropdownMenu>\n</template>\n\n<script setup lang=\"ts\">\nimport IconCog from '~icons/zondicons/cog';\n\nimport { Button, DropdownMenu, SettingsModal } from '@aerogel/core';\n\nimport AccountLoginModal from './AccountLoginModal.vue';\n</script>\n","<template>\n <AccountLoggedIn v-if=\"$solid.hasLoggedIn()\" />\n <AccountLoggedOut v-else />\n</template>\n\n<script setup lang=\"ts\">\nimport AccountLoggedIn from './AccountLoggedIn.vue';\nimport AccountLoggedOut from './AccountLoggedOut.vue';\n</script>\n","import { App, bootServices } from '@aerogel/core';\nimport type { Plugin } from '@aerogel/core';\n\nimport Cloud from '@aerogel/plugin-local-first/services/Cloud';\nimport { DEFAULT_STATE } from '@aerogel/plugin-local-first/services/Cloud.state';\n\nimport settings from './components/settings';\n\nconst services = { $cloud: Cloud };\n\nexport { Cloud };\nexport * from './components';\nexport * from './services/Cloud';\n\nexport interface Options {\n manualSetup?: boolean;\n}\n\nexport type LocalFirstServices = typeof services;\n\nexport default function localFirst(options: Options = {}): Plugin {\n return {\n name: '@aerogel/local-first',\n async install(app) {\n settings.forEach((setting) => App.addSetting(setting));\n\n if (typeof options.manualSetup === 'boolean') {\n DEFAULT_STATE.manualSetup = options.manualSetup;\n Cloud.manualSetup = options.manualSetup;\n }\n\n await bootServices(app, services);\n },\n };\n}\n\ndeclare module '@aerogel/core' {\n interface Services extends LocalFirstServices {}\n}\n"],"names":["containerRelations","getContainerRegisteredClasses","modelClass","arrayFilter","getContainerRelations","relation","relatedClass","isContainerClass","SolidModel","SolidContainsRelation","getContainedModels","model","models","getRelatedClasses","relatedClasses","instance","getRelatedAppModels","related","isInstanceOf","SolidACLAuthorization","SolidDocument","SolidResource","Metadata","Operation","SolidContainer","isDirtyOrHasDirtyChildren","relationHasDirtyModels","_a","relatedModel","loadAppRelations","onError","builtInRelations","updated","relatedModels","SolidIsContainedByRelation","error","Cloud","required","App","SyncQueue","__publicField","after","operationOrPromise","promise","arrayRemove","children","isContainer","child","SyncQueue$1","facade","remoteClasses","localClasses","cloneConstructors","getRelationClasses","visited","cleanRemoteModelClone","remoteModel","fixRemoteModelClone","operations","operation","PropertyOperation","createRemoteModel","localModel","isRegisteredModelClass","trackModelsCollection","requireUrlParentDirectory","createRemoteContainer","localModels","RemoteContainer","getRemoteClass","path","registeredModelClass","getRemoteContainersCollection","getLocalModel","collection","trackSoukaiModelsCollection","updateRemoteModel","ignoreModelUpdates","modelUpdates","clearLocalModelUpdates","syncedModelUrls","documentsWithErrors","localModelUpdates","syncedModelUrlsArray","url","count","documentUrl","urlRoute","modelUrl","cloneLocalModel","options","constructors","localClass","tap","cloneRemoteModel","getCloneConstructors","completeRemoteModels","remoteModels","RemoteTombstone","Tombstone","remoteModelUrls","missingModelDocumentUrls","tombstones","_b","otherClass","isRemoteModelClass","getLocalClass","a","b","constructor","getLocalModels","getTrackedModels","getSchemaMigrations","clearSchemaMigrations","getSchemaMigration","makeRemoteClass","rootStorage","Solid","containedClass","urlResolveDirectory","getRemoteModel","isRegisteredModel","registeredModel","isRemoteModel","isLocalModel","LocalClass","withLocalHistoryConfig","RemoteClass","attributes","exists","schema","bootModels","remoteClass","fail","Backup","Job","local","remote","engine","requireEngine","collections","droppedCollections","documents","localUrl","document","remoteUrl","solidCollections","filteredCollections","ignoreModelsCollection","localCollection","remoteCollection","key","value","lazy","getter","result","LoadsChildren","container","relationModels","arrayFrom","resourceUrlChunks","arrayChunk","statusChildren","statusChildrenMap","map","updateProgress","resourceUrls","resourceUrl","resource","type","documentChildren","documentTombstones","documentModels","childrenArray","engineDocuments","remoteEngine","_c","readDocument","documentModel","DocumentNotFound","found","relationInstance","typeIndexes","LoadsTypeIndex","user","TracksLocalModels","BaseJob","Migrate","mixed","status","job","childrenStatus","objectMap","modelStatuses","typeIndex","modelStatus","registeredClasses","registration","instanceContainer","migratedModel","migratedOperation","childStatus","isRootStatus","Sync","updateDocumentDate","headers","fallbackDate","date","clearListener","metadata","typedNavigator","Errors","lock","round","remoteModelsArray","localDocuments","index","documentsCache","tombstoneDocuments","tombstone","modifiedAt","pullStatus","registrations","containerModels","containerUrl","update","foundDocuments","childModels","processedContainerUrls","registeredModels","registeredChildren","childrenClass","rdfsClasses","rdfsClass","match","containerUrls","processedModels","wasDirty","arrayWithout","childrenStatuses","synchronizedModelUrls","deletedModels","dirtyRemoteModels","remoteRelatedModels","localRelatedModel","localRelation","remoteRelation","newLocalModelUrls","newRemoteModelUrls","MalformedSolidDocumentError","InvalidModelAttributes","primaryKey","requireBootedModel","toString","CloudStatus","DEFAULT_STATE","Service","defineServiceState","state","replaceExisting","migrationJob","total","ready","translateWithDefault","CloudService","Semaphore","callback","resolve","onReady","Events","modelUrlMappings","config","isArray","start","syncDirty","syncs","dispatch","isTesting","listener","removeListeners","removeListener","registered","rootCollection","trackModels","DocumentsCache","appNamespace","authenticator","watchEffect","urls","dirtyLocalModels","containedModel","hasLocationQueryParameter","parseBoolean","getLocationQueryParameter","getBootedModels","isSolidModel","_createBlock","_unref","Modal","$td","_createVNode","Markdown","Link","_cache","$event","$ui","SolidLogin","purgeData","UI","AccountLoginModal","Storage","$solid","_openBlock","_createElementBlock","_hoisted_1","_createElementVNode","_hoisted_2","_toDisplayString","Button","IconTrash","_hoisted_3","settings","defineSettings","PurgeData","close","useModal","cancellingSync","ref","pollingText","computed","errorDescription","showErrorDetails","cancelSync","useEvent","SolidAvatar","SettingsModal","IconCog","_hoisted_4","$cloud","_hoisted_5","IconRefresh","_hoisted_6","ProgressBar","_hoisted_7","_hoisted_8","IconWarning","$errors","_hoisted_10","_hoisted_11","IconCheckmarkOutline","_normalizeClass","_hoisted_12","_hoisted_9","AdvancedOptions","_hoisted_13","Checkbox","_hoisted_14","_hoisted_15","EditableContent","_hoisted_16","_hoisted_17","IconStop","IconCloudUpload","IconLogout","accountStatus","getAccountStatusMessage","AccountModal","DropdownMenu","AccountLoggedIn","AccountLoggedOut","services","localFirst","app","setting","bootServices"],"mappings":";;;;;;;;;;;AAiBA,MAAMA,yBAA+D,QAAA;AAG9D,SAASC,GAA8BC,GAAgE;AAC1G,SAAOC;AAAA,IACHC,EAAsBF,CAAU,EAAE,IAAI,CAACG,MAAa;AAChD,YAAMC,IAAeJ,EAAW,SAAA,EAAW,gBAAuCG,CAAQ,EAAE;AAE5F,aAAIE,EAAiBD,CAAY,IACtB,KAGJA;AAAA,IACX,CAAC;AAAA,EAAA;AAET;AAEO,SAASF,EAAsBF,GAAyC;AAC3E,SAAKF,GAAmB,IAAIE,CAAU,KAClCF,GAAmB;AAAA,IACfE;AAAA,IACAA,EAAW,UAAU,OAAO,CAACG,MACrBG,EAAW,kBAAkB,SAASH,CAAQ,IACvC,KAGcH,EAAW,SAAA,EAAW,gBAAgBG,CAAQ,aAEpCI,EACtC;AAAA,EAAA,GAIFT,GAAmB,IAAIE,CAAU,KAAK,CAAA;AACjD;AAEO,SAASQ,GAAmBC,GAAqC;AAGpE,SAFkBP,EAAsBO,EAAM,OAAA,CAAQ,EAErC;AAAA,IACb,CAACC,GAAQP,MAAaO,EAAO,OAAOD,EAAM,kBAAkBN,CAAQ,KAAK,EAAE;AAAA,IAC3E,CAAA;AAAA,EAAC;AAET;AAEO,SAASQ,GAAkBX,GAA4D;AAC1F,QAAMY,wBAAqB,IAAA,GACrBC,IAAWb,EAAW,SAAA;AAE5B,EAAAY,EAAe,IAAI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EAA0BH,EAAAuC,EAAA,GAAA,EAAjB,OAAM,UAAQ;AAAA,UAAA;;;;;;;;;;qBCbRzB,EAAAA,OAAO,YAAA,UAA9Bf,EAA+CwE,IAAA,EAAA,KAAA,GAAA,WAC/CxE,EAA2ByE,IAAA,EAAA,KAAA,GAAA;AAAA;ICMzBC,KAAW,EAAE,QAAQ9U,EAAA;AAY3B,SAAwB+U,GAAWzR,IAAmB,IAAY;AAC9D,SAAO;AAAA,IACH,MAAM;AAAA,IACN,MAAM,QAAQ0R,GAAK;AACf,MAAAnD,GAAS,QAAQ,CAACoD,MAAY/U,EAAI,WAAW+U,CAAO,CAAC,GAEjD,OAAO3R,EAAQ,eAAgB,cAC/BqK,GAAc,cAAcrK,EAAQ,aACpCtD,EAAM,cAAcsD,EAAQ,cAGhC,MAAM4R,GAAaF,GAAKF,EAAQ;AAAA,IACpC;AAAA,EAAA;AAER;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aerogel/plugin-local-first",
3
- "version": "0.1.2-next.823beb2779ebc4c5272f5e4e094cecc32cffa527",
3
+ "version": "0.1.2",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "exports": {
@@ -30,23 +30,17 @@
30
30
  "soukai-solid": "*"
31
31
  },
32
32
  "dependencies": {
33
- "@noeldemartin/solid-utils": "catalog:",
34
- "@noeldemartin/utils": "catalog:",
35
- "idb": "catalog:"
33
+ "@noeldemartin/solid-utils": "^0.6.1",
34
+ "@noeldemartin/utils": "0.7.3",
35
+ "idb": "^8.0.2"
36
36
  },
37
37
  "devDependencies": {
38
- "@aerogel/core": "workspace:*",
39
- "@aerogel/plugin-solid": "workspace:*",
40
- "@aerogel/plugin-soukai": "workspace:*",
41
- "@aerogel/vite": "workspace:*",
42
- "@arethetypeswrong/cli": "catalog:",
43
- "@noeldemartin/scripts": "catalog:",
44
- "@types/node": "catalog:",
45
- "eslint": "catalog:",
38
+ "@aerogel/core": "*",
39
+ "@aerogel/plugin-solid": "*",
40
+ "@aerogel/plugin-soukai": "*",
46
41
  "fake-indexeddb": "^6.0.0",
47
- "publint": "catalog:",
48
- "soukai": "catalog:",
49
- "soukai-solid": "catalog:"
42
+ "soukai": "*",
43
+ "soukai-solid": "*"
50
44
  },
51
45
  "eslintConfig": {
52
46
  "extends": [
@@ -63,7 +63,7 @@ export class CloudService extends Service {
63
63
 
64
64
  protected asyncLock: Semaphore = new Semaphore();
65
65
  protected engine: Engine | null = null;
66
- protected pollingInterval: ReturnType<typeof setInterval> | null = null;
66
+ protected pollingInterval: NodeJS.Timeout | null = null;
67
67
  protected documentsCache: DocumentsCache | null = null;
68
68
 
69
69
  public async whenReady<T>(callback: () => T): Promise<T> {