@seedprotocol/sdk 0.3.8 → 0.3.9
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.
- package/dist/addModel.js +4 -0
- package/dist/addModel.js.map +1 -1
- package/dist/main.js +11 -0
- package/dist/main.js.map +1 -1
- package/dist/src/ItemProperty/index.js +4 -0
- package/dist/src/ItemProperty/index.js.map +1 -0
- package/dist/src/browser/db/Db.d.ts.map +1 -1
- package/dist/src/browser/db/Db.js +35 -8
- package/dist/src/browser/db/Db.js.map +1 -1
- package/dist/src/browser/helpers/FileManager.d.ts +2 -0
- package/dist/src/browser/helpers/FileManager.d.ts.map +1 -1
- package/dist/src/browser/helpers/FileManager.js +20 -8
- package/dist/src/browser/helpers/FileManager.js.map +1 -1
- package/dist/src/browser/index.d.ts +0 -1
- package/dist/src/browser/index.d.ts.map +1 -1
- package/dist/src/browser/react/index.d.ts +2 -1
- package/dist/src/browser/react/index.d.ts.map +1 -1
- package/dist/src/browser/react/model.d.ts +7 -0
- package/dist/src/browser/react/model.d.ts.map +1 -0
- package/dist/src/browser/react/model.js +20 -0
- package/dist/src/browser/react/model.js.map +1 -0
- package/dist/src/browser/react/services.js +1 -1
- package/dist/src/browser/react/services.js.map +1 -1
- package/dist/src/browser/workers/FileDownloader.d.ts.map +1 -1
- package/dist/src/browser/workers/FileDownloader.js +3 -1
- package/dist/src/browser/workers/FileDownloader.js.map +1 -1
- package/dist/src/client/ClientManager.d.ts +21 -12
- package/dist/src/client/ClientManager.d.ts.map +1 -1
- package/dist/src/client/ClientManager.js +21 -0
- package/dist/src/client/ClientManager.js.map +1 -1
- package/dist/src/client/actors/saveAppState.d.ts.map +1 -1
- package/dist/src/client/actors/saveAppState.js +0 -1
- package/dist/src/client/actors/saveAppState.js.map +1 -1
- package/dist/src/db/read/getModels.d.ts +2 -0
- package/dist/src/db/read/getModels.d.ts.map +1 -0
- package/dist/src/events/files/download.d.ts.map +1 -1
- package/dist/src/events/files/download.js +0 -1
- package/dist/src/events/files/download.js.map +1 -1
- package/dist/src/events/files/index.d.ts.map +1 -1
- package/dist/src/events/files/index.js +0 -1
- package/dist/src/events/files/index.js.map +1 -1
- package/dist/src/events/services/allItems.d.ts.map +1 -1
- package/dist/src/events/services/allItems.js +0 -1
- package/dist/src/events/services/allItems.js.map +1 -1
- package/dist/src/helpers/FileManager/BaseFileManager.d.ts +2 -0
- package/dist/src/helpers/FileManager/BaseFileManager.d.ts.map +1 -1
- package/dist/src/helpers/FileManager/BaseFileManager.js +6 -0
- package/dist/src/helpers/FileManager/BaseFileManager.js.map +1 -1
- package/dist/src/helpers/environment.js +1 -1
- package/dist/src/helpers/environment.js.map +1 -1
- package/dist/src/index.d.ts +8 -1
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/node/helpers/FileManager.d.ts +2 -0
- package/dist/src/node/helpers/FileManager.d.ts.map +1 -1
- package/dist/src/node/helpers/index.d.ts.map +1 -1
- package/dist/src/node/helpers/index.js +0 -1
- package/dist/src/node/helpers/index.js.map +1 -1
- package/dist/src/services/db/actors/migrate.js +1 -1
- package/dist/src/services/db/actors/migrate.js.map +1 -1
- package/dist/src/services/internal/helpers.js +3 -3
- package/dist/src/services/internal/helpers.js.map +1 -1
- package/dist/src/types/model.d.ts +2 -15
- package/dist/src/types/model.d.ts.map +1 -1
- package/package.json +7 -7
package/dist/addModel.js
CHANGED
|
@@ -72,6 +72,10 @@ const injectModel = (schemaContent, newModelCode) => {
|
|
|
72
72
|
updatedSchema.slice(modelsClosingBracePos);
|
|
73
73
|
return updatedSchema;
|
|
74
74
|
};
|
|
75
|
+
if (fileContents.includes(`class ${jsonModel.name}`)) {
|
|
76
|
+
console.error(`Model with name ${jsonModel.name} already exists in the schema`);
|
|
77
|
+
process.exit(0);
|
|
78
|
+
}
|
|
75
79
|
const newModelCode = generateModelCode({
|
|
76
80
|
modelName: jsonModel.name,
|
|
77
81
|
properties: jsonModel.properties,
|
package/dist/addModel.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"addModel.js","sources":["../../scripts/addModel.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport fs from 'fs';\nimport {
|
|
1
|
+
{"version":3,"file":"addModel.js","sources":["../../scripts/addModel.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport fs from 'fs';\nimport { generateModelCode } from '../src/node/codegen/drizzle';\n\n// Parse command line arguments\nconst args = process.argv.slice(2);\nconst sourceSchemaFilePath = args[0];\nconst outputFilePath = args[1];\nconst jsonString = args[2];\n\nif (!sourceSchemaFilePath || !outputFilePath || !jsonString) {\n console.error('Usage: npx tsx bin/addModel.ts <source-schema-file-path> <output-file-path> <json-string>');\n process.exit(1);\n}\n\n// Read the contents of the file\nlet fileContents;\ntry {\n fileContents = fs.readFileSync(sourceSchemaFilePath, 'utf-8');\n} catch (error) {\n console.error(`Error reading file at ${sourceSchemaFilePath}:`, error);\n process.exit(1);\n}\n\n// Parse the JSON string\nlet jsonModel;\ntry {\n jsonModel = JSON.parse(jsonString);\n} catch (error) {\n console.error('Invalid JSON string:', error);\n process.exit(1);\n}\n\n/**\n * Simple function to inject a new model after the last model class and update the models object\n * @param {string} schemaContent - The content of the schema file\n * @param {string} newModelCode - The code for the new model to inject\n * @returns {string} The updated schema content\n */\nconst injectModel = (schemaContent: string, newModelCode: string) => {\n // Extract the model name from the new code\n const modelNameMatch = newModelCode.match(/class\\s+(\\w+)/);\n if (!modelNameMatch) {\n throw new Error(\"Could not extract model name from provided code\");\n }\n const modelName = modelNameMatch[1];\n\n // Find the 'const models' position\n const modelsPos = schemaContent.indexOf('const models');\n if (modelsPos === -1) {\n throw new Error(\"Could not find 'const models' in the schema\");\n }\n\n // Find the position of the last model class before 'const models'\n const lastClassPos = schemaContent.lastIndexOf('@Model', modelsPos);\n if (lastClassPos === -1) {\n throw new Error(\"Could not find any model declarations in the schema\");\n }\n\n // Find the end of the last class\n const classEndPos = schemaContent.indexOf('}', lastClassPos);\n if (classEndPos === -1) {\n throw new Error(\"Could not find closing brace of the last model class\");\n }\n\n // Find the position after the last class's closing brace\n const insertModelPos = schemaContent.indexOf('\\n', classEndPos) + 1;\n \n // Insert the new model\n let updatedSchema = \n schemaContent.slice(0, insertModelPos) + \n \"\\n\" + newModelCode + \"\\n\\n\" + \n schemaContent.slice(insertModelPos);\n \n // Find the closing brace of the models object\n const modelsClosingBracePos = updatedSchema.indexOf('}', updatedSchema.indexOf('const models'));\n \n // Add the new model to the models object\n updatedSchema = \n updatedSchema.slice(0, modelsClosingBracePos) + \n ` ${modelName},\\n` + \n updatedSchema.slice(modelsClosingBracePos);\n \n return updatedSchema;\n}\n\nif (fileContents.includes(`class ${jsonModel.name}`)) {\n console.error(`Model with name ${jsonModel.name} already exists in the schema`);\n process.exit(0);\n}\n\nconst newModelCode = generateModelCode({\n modelName: jsonModel.name,\n properties: jsonModel.properties,\n});\n\nconst updatedSchema = injectModel(fileContents, newModelCode);\n\n// Write the new table file\ntry {\n fs.writeFileSync(outputFilePath, updatedSchema, 'utf-8');\n console.log(`Wrote updated schema file to ${outputFilePath}`);\n} catch (error) {\n console.error('Error writing Drizzle table file:', error);\n process.exit(1);\n} \n"],"names":[],"mappings":";;;;AAKA;AACA,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;AAClC,MAAM,oBAAoB,GAAG,IAAI,CAAC,CAAC,CAAC;AACpC,MAAM,cAAc,GAAG,IAAI,CAAC,CAAC,CAAC;AAC9B,MAAM,UAAU,GAAG,IAAI,CAAC,CAAC,CAAC;AAE1B,IAAI,CAAC,oBAAoB,IAAI,CAAC,cAAc,IAAI,CAAC,UAAU,EAAE;AAC3D,IAAA,OAAO,CAAC,KAAK,CAAC,2FAA2F,CAAC;AAC1G,IAAA,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC;AACjB;AAEA;AACA,IAAI,YAAY;AAChB,IAAI;IACF,YAAY,GAAG,EAAE,CAAC,YAAY,CAAC,oBAAoB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AAC;AACzD,IAAA,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC;AACjB"}
|
package/dist/main.js
CHANGED
|
@@ -3,11 +3,22 @@ import 'reflect-metadata';
|
|
|
3
3
|
export { Model } from './src/schema/model/index.js';
|
|
4
4
|
export { Boolean, Date, Image, Json, List, Number, Property, Relation, Text } from './src/schema/property/index.js';
|
|
5
5
|
export { Item } from './src/Item/index.js';
|
|
6
|
+
export { ItemProperty } from './src/ItemProperty/index.js';
|
|
6
7
|
export { useCreateItem, useItem, useItems, usePublishItem } from './src/browser/react/item.js';
|
|
7
8
|
export { useItemProperties, useItemProperty } from './src/browser/react/property.js';
|
|
8
9
|
export { useGlobalServiceStatus, usePersistedSnapshots, useService, useServices } from './src/browser/react/services.js';
|
|
9
10
|
import './src/browser/react/db.js';
|
|
10
11
|
export { useDeleteItem } from './src/browser/react/trash.js';
|
|
12
|
+
export { useModels } from './src/browser/react/model.js';
|
|
13
|
+
export { FileManager as FileManagerBrowser } from './src/browser/helpers/FileManager.js';
|
|
14
|
+
export { Db as DbBrowser } from './src/browser/db/Db.js';
|
|
15
|
+
export { seeds } from './src/seedSchema/SeedSchema.js';
|
|
16
|
+
export { versions } from './src/seedSchema/VersionSchema.js';
|
|
17
|
+
export { metadata } from './src/seedSchema/MetadataSchema.js';
|
|
18
|
+
import './src/seedSchema/AppStateSchema.js';
|
|
19
|
+
export { models } from './src/seedSchema/ModelSchema.js';
|
|
20
|
+
import './src/seedSchema/ModelUidSchema.js';
|
|
21
|
+
export { getModel, getModelNames, getModels } from './src/stores/modelClass.js';
|
|
11
22
|
export { getCorrectId } from './src/helpers/index.js';
|
|
12
23
|
export { eventEmitter } from './src/eventBus.js';
|
|
13
24
|
export { withSeed } from './src/node/webpack/index.js';
|
package/dist/main.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"main.js","sources":["../../src/index.ts"],"sourcesContent":["import { enableMapSet } from 'immer'\n\nexport {\n Model,\n Property,\n Image,\n List,\n Text,\n Json,\n Relation,\n Boolean,\n Number,\n Date,\n} from './schema'\n\
|
|
1
|
+
{"version":3,"file":"main.js","sources":["../../src/index.ts"],"sourcesContent":["import { enableMapSet } from 'immer'\n\nexport {\n Model,\n Property,\n Image,\n List,\n Text,\n Json,\n Relation,\n Boolean,\n Number,\n Date,\n} from './schema'\n\nexport { Item } from './Item'\nexport { ItemProperty } from './ItemProperty'\n\nexport {\n useItems,\n useItem,\n useItemProperties,\n useCreateItem,\n useItemProperty,\n useDeleteItem,\n useGlobalServiceStatus,\n usePublishItem,\n usePersistedSnapshots,\n useServices,\n useService,\n useModels,\n} from './browser/react'\n\nexport {FileManager as FileManagerBrowser} from './browser/helpers/FileManager'\nexport {Db as DbBrowser} from './browser/db/Db'\n\nexport {models, versions, seeds, metadata, } from './seedSchema'\n\nexport {getModels, getModel, getModelNames,} from './stores/modelClass'\n\nexport { getCorrectId, } from './helpers'\n\nexport {\n eventEmitter,\n} from './eventBus'\n\nenableMapSet()\n\nexport { withSeed } from './node/webpack'\n\nexport type { PublishUpload } from './db/read/getPublishUploads'\n\n\nexport { client } from './client'\n\nexport * from './types'\n\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,YAAY,EAAE"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../../../../src/ItemProperty/index.ts"],"sourcesContent":["import { isBrowser } from '@/helpers/environment'\nimport { BaseItemProperty } from '@/ItemProperty/BaseItemProperty'\n\nlet ItemProperty: typeof BaseItemProperty | undefined\n\nexport const initItemProperty = async () => {\n\n if (isBrowser()) {\n ItemProperty = (await import('../browser/ItemProperty/ItemProperty')).ItemProperty\n }\n\n if (!isBrowser()) {\n ItemProperty = (await import('../node/ItemProperty/ItemProperty')).ItemProperty\n }\n}\n\nexport { ItemProperty }"],"names":[],"mappings":"AAGA,IAAI;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Db.d.ts","sourceRoot":"","sources":["../../../../src/browser/db/Db.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AACxC,OAAO,EAAE,GAAG,EAAE,MAAM,kBAAkB,CAAC;AAIvC,OAAO,EAAW,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;
|
|
1
|
+
{"version":3,"file":"Db.d.ts","sourceRoot":"","sources":["../../../../src/browser/db/Db.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AACxC,OAAO,EAAE,GAAG,EAAE,MAAM,kBAAkB,CAAC;AAIvC,OAAO,EAAW,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AAQzE,cAAM,EAAG,SAAQ,MAAO,YAAW,GAAG;IAEpC,MAAM,CAAC,gBAAgB,EAAE,GAAG,CAAA;IAC5B,MAAM,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAA;IACnC,MAAM,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAA;IACnC,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,CAAA;IAC/B,MAAM,CAAC,KAAK,EAAE,oBAAoB,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,GAAG,SAAS,CAAA;;IAMvE,MAAM,CAAC,QAAQ;IAIf,MAAM,CAAC,YAAY;WAIN,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAI,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC;WAyE3D,OAAO,CAAC,WAAW,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAI,OAAO,CAAC,IAAI,CAAC;WA0L5D,IAAI,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE;CAiC7C;AAED,OAAO,EAAE,EAAE,EAAE,CAAA"}
|
|
@@ -6,7 +6,6 @@ import { drizzle } from 'drizzle-orm/sqlite-proxy';
|
|
|
6
6
|
import { migrate } from 'drizzle-orm/sqlite-proxy/migrator';
|
|
7
7
|
import { DB_NAME_APP, BROWSER_FS_TOP_DIR } from '../../services/internal/constants.js';
|
|
8
8
|
import '../../helpers/index.js';
|
|
9
|
-
import { sqlite3Worker1Promiser } from '@sqlite.org/sqlite-wasm';
|
|
10
9
|
import { BaseFileManager } from '../../helpers/FileManager/BaseFileManager.js';
|
|
11
10
|
|
|
12
11
|
const logger = debug('seedSdk:browser:db:Db');
|
|
@@ -25,13 +24,35 @@ class Db extends BaseDb {
|
|
|
25
24
|
return this.dbId;
|
|
26
25
|
}
|
|
27
26
|
this.filesDir = filesDir;
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
27
|
+
if (typeof document === 'undefined') {
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
let promiser;
|
|
31
|
+
try {
|
|
32
|
+
let sqlite3Worker1Promiser;
|
|
33
|
+
const sqliteWasm = await import('@sqlite.org/sqlite-wasm');
|
|
34
|
+
if (sqliteWasm && sqliteWasm.sqlite3Worker1Promiser) {
|
|
35
|
+
sqlite3Worker1Promiser = sqliteWasm.sqlite3Worker1Promiser;
|
|
36
|
+
}
|
|
37
|
+
if (!sqlite3Worker1Promiser && window.sqlite3Worker1Promiser) {
|
|
38
|
+
sqlite3Worker1Promiser = window.sqlite3Worker1Promiser;
|
|
39
|
+
}
|
|
40
|
+
if (!sqlite3Worker1Promiser) {
|
|
41
|
+
throw new Error('Failed to load sqlite3Worker1Promiser');
|
|
42
|
+
}
|
|
43
|
+
promiser = await new Promise((resolve) => {
|
|
44
|
+
const _promiser = sqlite3Worker1Promiser({
|
|
45
|
+
onready: () => {
|
|
46
|
+
resolve(_promiser);
|
|
47
|
+
},
|
|
48
|
+
});
|
|
49
|
+
}).catch((error) => {
|
|
50
|
+
console.error('Error from sqlite proxy server: ', JSON.stringify(error));
|
|
33
51
|
});
|
|
34
|
-
}
|
|
52
|
+
}
|
|
53
|
+
catch (e) {
|
|
54
|
+
console.error('Error from sqlite proxy server: ', JSON.stringify(e));
|
|
55
|
+
}
|
|
35
56
|
if (!promiser) {
|
|
36
57
|
throw new Error('Failed to create promiser');
|
|
37
58
|
}
|
|
@@ -124,7 +145,13 @@ class Db extends BaseDb {
|
|
|
124
145
|
}
|
|
125
146
|
catch (error) {
|
|
126
147
|
await BaseFileManager.waitForFile(`${pathToDbDir}/meta/_journal.json`);
|
|
127
|
-
await
|
|
148
|
+
const journalExists = await BaseFileManager.pathExists(`${pathToDbDir}/meta/_journal.json`);
|
|
149
|
+
if (journalExists) {
|
|
150
|
+
await this.migrate(pathToDbDir, dbName);
|
|
151
|
+
}
|
|
152
|
+
if (!journalExists) {
|
|
153
|
+
throw new Error('Failed to migrate database');
|
|
154
|
+
}
|
|
128
155
|
}
|
|
129
156
|
this.appDb = drizzleDb;
|
|
130
157
|
// const createTempTableQuery = await appDb.run(
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Db.js","sources":["../../../../../src/browser/db/Db.ts"],"sourcesContent":["import { BaseDb } from \"@/db/Db/BaseDb\";\nimport { IDb } from \"@/interfaces/IDb\";\nimport debug from \"debug\";\nimport { sql } from \"drizzle-orm\";\nimport { readMigrationFiles } from \"drizzle-orm/migrator\";\nimport { drizzle, SqliteRemoteDatabase } from \"drizzle-orm/sqlite-proxy\";\nimport { migrate as drizzleMigrate } from \"drizzle-orm/sqlite-proxy/migrator\";\nimport { BROWSER_FS_TOP_DIR, DB_NAME_APP } from \"@/services/internal/constants\";\nimport { BaseFileManager } from \"@/helpers\";\nimport { sqlite3Worker1Promiser, } from \"@sqlite.org/sqlite-wasm\";\n\nconst logger = debug('seedSdk:browser:db:Db')\n\n\nclass Db extends BaseDb implements IDb {\n\n static sqliteWasmClient: any\n static filesDir: string | undefined\n static pathToDb: string | undefined\n static dbId: string | undefined\n static appDb: SqliteRemoteDatabase<Record<string, unknown>> | undefined\n\n constructor() {\n super()\n }\n\n static getAppDb() {\n return this.appDb\n }\n\n static isAppDbReady() {\n return !!this.appDb\n }\n\n static async connectToDb(filesDir: string,): Promise<string | undefined> {\n\n if (Db.sqliteWasmClient) {\n return this.dbId\n }\n\n this.filesDir = filesDir\n\n const promiser = await new Promise<(event: string, config: Record<string, unknown>) => Promise<any>>((resolve) => {\n const _promiser = sqlite3Worker1Promiser({\n onready: () => {\n resolve(_promiser);\n },\n });\n });\n\n if (!promiser) {\n throw new Error('Failed to create promiser')\n }\n\n this.sqliteWasmClient = promiser\n\n const responseGet = await this.sqliteWasmClient('config-get', {});\n\n logger('[Db.prepareDb] Running SQLite3 version', responseGet.result.version.libVersion);\n\n const responseOpen = await this.sqliteWasmClient('open', {\n filename: `file:${filesDir}/db/${DB_NAME_APP}.sqlite3?vfs=opfs`,\n });\n const { dbId } = responseOpen;\n logger(\n '[Db.prepareDb] OPFS is available, created persisted database at',\n responseOpen.result.filename.replace(/^file:(.*?)\\?vfs=opfs/, '$1'),\n );\n\n logger('[Db.prepareDb] dbId', dbId) \n\n this.dbId = dbId\n\n return dbId\n }\n\n static async migrate(pathToDbDir: string, dbName: string,): Promise<void> {\n\n const schemaGlobString = `${BROWSER_FS_TOP_DIR}/schema/*`\n\n const drizzleDb = drizzle(\n async (sql, params, method) => {\n try {\n // logger(\n // `executing sql on ${dbName} with id: ${dbId} and method: ${method}`,\n // sql,\n // )\n\n const finalResult = await this.exec(sql, params)\n\n // logger(`finalResult with method: ${method}`, finalResult)\n // Drizzle always waits for {rows: string[][]} or {rows: string[]} for the return value.\n\n // When the method is get, you should return a value as {rows: string[]}.\n // Otherwise, you should return {rows: string[][]}.\n\n return { rows: finalResult }\n } catch (e: any) {\n console.error('Error from sqlite proxy server: ', JSON.stringify(e))\n return { rows: [] }\n }\n },\n {\n schema: schemaGlobString,\n // logger: true,\n },\n )\n\n try {\n const zenfs = await BaseFileManager.getFs()\n\n const filesInRoot = await zenfs.promises.readdir('/')\n logger('filesInRoot', filesInRoot)\n const migrations = readMigrationFiles({\n migrationsFolder: pathToDbDir,\n })\n\n if (migrations.length > 0) {\n const incomingMigrationHashes = migrations.map(\n (migration) => migration.hash,\n )\n\n let existingMigrationHashes\n let rows = []\n\n try {\n\n const queryMigrationsTable = await drizzleDb.run(\n sql.raw(\n `SELECT name \n FROM sqlite_master \n WHERE type='table' \n AND name='__drizzle_migrations';`,\n ),\n )\n\n logger('queryMigrationsTable', queryMigrationsTable)\n\n if (queryMigrationsTable && queryMigrationsTable.rows && queryMigrationsTable.rows.length > 0) {\n const query = await drizzleDb.run(\n sql.raw(\n `SELECT hash, created_at\n FROM main.__drizzle_migrations;`,\n ),\n )\n \n rows = query.rows\n }\n\n } catch (e) {\n rows = []\n }\n\n if (rows && rows.length > 0) {\n existingMigrationHashes = rows.map((row) => row[0])\n }\n\n if (existingMigrationHashes) {\n let shouldRebuildDb = false\n for (const existingHash of existingMigrationHashes) {\n if (!incomingMigrationHashes.includes(existingHash)) {\n shouldRebuildDb = true\n break\n }\n }\n if (shouldRebuildDb) {\n await zenfs.promises.unlink(`${pathToDbDir}/${dbName}.sqlite3`)\n }\n }\n }\n\n await drizzleMigrate(\n drizzleDb,\n async (queriesToRun) => {\n // logger('queriesToRun', queriesToRun)\n for (const query of queriesToRun) {\n // logger('query', query)\n await drizzleDb.run(sql.raw(query))\n }\n },\n {\n migrationsFolder: pathToDbDir,\n },\n )\n } catch (error) {\n\n await BaseFileManager.waitForFile(`${pathToDbDir}/meta/_journal.json`)\n\n await this.migrate(pathToDbDir, dbName,)\n\n }\n\n this.appDb = drizzleDb\n // const createTempTableQuery = await appDb.run(\n // sql.raw(\n // `CREATE TEMP TABLE IF NOT EXISTS temp_last_inserted_id (id INTEGER, table TEXT);`,\n // ),\n // )\n //\n // logger(\n // '[db/actors] [migrate] createTempTableQuery',\n // createTempTableQuery,\n // )\n\n // const triggersQuery = await appDb.run(\n // sql.raw(\n // `SELECT name\n // FROM main.sqlite_master\n // WHERE type = 'trigger';`,\n // ),\n // )\n //\n // logger('[db/actors] [migrate] triggersQuery', triggersQuery)\n //\n // const triggers = triggersQuery.rows.map((row) => row[0])\n //\n // const tablesQuery = await appDb.run(\n // sql.raw(\n // `SELECT name\n // FROM main.sqlite_master\n // WHERE type = 'table';`,\n // ),\n // )\n //\n // logger('[db/actors] [migrate] tablesQuery', tablesQuery)\n //\n // const tableNames = tablesQuery.rows.map((row) => row[0])\n // logger('[db/actors] [migrate] tableNames', tableNames)\n // for (const tableName of tableNames) {\n // const triggerName = `after_insert_${tableName}`\n // if (triggers.includes(triggerName)) {\n // continue\n // }\n // const createTriggerQuery = await appDb.run(\n // sql.raw(\n // `CREATE TRIGGER after_insert_${tableName}\n // AFTER INSERT ON ${tableName}\n // BEGIN\n // DELETE FROM temp_last_inserted_id;\n // INSERT INTO temp_last_inserted_id (id) VALUES (new.id);\n // END;`,\n // ),\n // )\n //\n // logger(\n // '[db/actors] [migrate] createTriggerQuery',\n // createTriggerQuery,\n // )\n // }\n }\n\n static async exec(sql: string, params: any[]) {\n const rowsToReturnRaw: SqliteWasmResult[] = []\n const rowsValues: string[][] = []\n \n // For a single exec command, the callback potentially gets called several times -- once for each row.\n // So we need to collect all rows into a final array to return (execResult).\n const rowsToReturn = await new Promise((resolve, reject) => {\n\n\n this.sqliteWasmClient('exec', {\n dbId:this.dbId,\n sql,\n bind: params,\n callback: (result) => {\n // Checks if this is the final callback of the query\n if (!result || !result.row || !result.rowNumber) {\n const returnResult = []\n for (const currRow of rowsToReturnRaw) {\n returnResult.push(currRow.row)\n }\n resolve(returnResult)\n } else {\n // If not the final response, add this row to the return array\n rowsToReturnRaw.push(result)\n }\n },\n }).catch(async (error) => {\n reject(error)\n })\n })\n \n return rowsToReturn || []\n }\n}\n\nexport { Db }"],"names":["drizzleMigrate"],"mappings":";;;;;;;;;;;AAWA,MAAM,MAAM,GAAG,KAAK,CAAC,uBAAuB,CAAC;AAG7C,MAAM,EAAG,SAAQ,MAAM,CAAA;AAQrB,IAAA,WAAA,GAAA;AACE,QAAA,KAAK,EAAE;;AAGT,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} from \"@/interfaces/IDb\";\nimport debug from \"debug\";\nimport { sql } from \"drizzle-orm\";\nimport { readMigrationFiles } from \"drizzle-orm/migrator\";\nimport { drizzle, SqliteRemoteDatabase } from \"drizzle-orm/sqlite-proxy\";\nimport { migrate as drizzleMigrate } from \"drizzle-orm/sqlite-proxy/migrator\";\nimport { BROWSER_FS_TOP_DIR, DB_NAME_APP } from \"@/services/internal/constants\";\nimport { BaseFileManager } from \"@/helpers\";\n\nconst logger = debug('seedSdk:browser:db:Db')\n\n\nclass Db extends BaseDb implements IDb {\n\n static sqliteWasmClient: any\n static filesDir: string | undefined\n static pathToDb: string | undefined\n static dbId: string | undefined\n static appDb: SqliteRemoteDatabase<Record<string, unknown>> | undefined\n\n constructor() {\n super()\n }\n\n static getAppDb() {\n return this.appDb\n }\n\n static isAppDbReady() {\n return !!this.appDb\n }\n\n static async connectToDb(filesDir: string,): Promise<string | undefined> {\n\n if (Db.sqliteWasmClient) {\n return this.dbId\n }\n\n this.filesDir = filesDir\n\n if (typeof document === 'undefined') {\n return\n }\n\n let promiser\n\n try {\n\n let sqlite3Worker1Promiser\n\n const sqliteWasm = await import('@sqlite.org/sqlite-wasm')\n\n if (sqliteWasm && sqliteWasm.sqlite3Worker1Promiser) {\n sqlite3Worker1Promiser = sqliteWasm.sqlite3Worker1Promiser\n }\n\n if (!sqlite3Worker1Promiser && window.sqlite3Worker1Promiser) {\n sqlite3Worker1Promiser = window.sqlite3Worker1Promiser\n }\n\n if (!sqlite3Worker1Promiser) {\n throw new Error('Failed to load sqlite3Worker1Promiser')\n }\n\n promiser = await new Promise<(event: string, config: Record<string, unknown>) => Promise<any>>((resolve) => {\n const _promiser = sqlite3Worker1Promiser({\n onready: () => {\n resolve(_promiser);\n },\n });\n }).catch((error) => {\n console.error('Error from sqlite proxy server: ', JSON.stringify(error))\n });\n\n } catch ( e ) {\n console.error('Error from sqlite proxy server: ', JSON.stringify(e))\n }\n\n\n if (!promiser) {\n throw new Error('Failed to create promiser')\n }\n\n this.sqliteWasmClient = promiser\n\n const responseGet = await this.sqliteWasmClient('config-get', {});\n\n logger('[Db.prepareDb] Running SQLite3 version', responseGet.result.version.libVersion);\n\n const responseOpen = await this.sqliteWasmClient('open', {\n filename: `file:${filesDir}/db/${DB_NAME_APP}.sqlite3?vfs=opfs`,\n });\n const { dbId } = responseOpen;\n logger(\n '[Db.prepareDb] OPFS is available, created persisted database at',\n responseOpen.result.filename.replace(/^file:(.*?)\\?vfs=opfs/, '$1'),\n );\n\n logger('[Db.prepareDb] dbId', dbId) \n\n this.dbId = dbId\n\n return dbId\n }\n\n static async migrate(pathToDbDir: string, dbName: string,): Promise<void> {\n\n const schemaGlobString = `${BROWSER_FS_TOP_DIR}/schema/*`\n\n const drizzleDb = drizzle(\n async (sql, params, method) => {\n try {\n // logger(\n // `executing sql on ${dbName} with id: ${dbId} and method: ${method}`,\n // sql,\n // )\n\n const finalResult = await this.exec(sql, params)\n\n // logger(`finalResult with method: ${method}`, finalResult)\n // Drizzle always waits for {rows: string[][]} or {rows: string[]} for the return value.\n\n // When the method is get, you should return a value as {rows: string[]}.\n // Otherwise, you should return {rows: string[][]}.\n\n return { rows: finalResult }\n } catch (e: any) {\n console.error('Error from sqlite proxy server: ', JSON.stringify(e))\n return { rows: [] }\n }\n },\n {\n schema: schemaGlobString,\n // logger: true,\n },\n )\n\n try {\n const zenfs = await BaseFileManager.getFs()\n\n const filesInRoot = await zenfs.promises.readdir('/')\n logger('filesInRoot', filesInRoot)\n const migrations = readMigrationFiles({\n migrationsFolder: pathToDbDir,\n })\n\n if (migrations.length > 0) {\n const incomingMigrationHashes = migrations.map(\n (migration) => migration.hash,\n )\n\n let existingMigrationHashes\n let rows = []\n\n try {\n\n const queryMigrationsTable = await drizzleDb.run(\n sql.raw(\n `SELECT name \n FROM sqlite_master \n WHERE type='table' \n AND name='__drizzle_migrations';`,\n ),\n )\n\n logger('queryMigrationsTable', queryMigrationsTable)\n\n if (queryMigrationsTable && queryMigrationsTable.rows && queryMigrationsTable.rows.length > 0) {\n const query = await drizzleDb.run(\n sql.raw(\n `SELECT hash, created_at\n FROM main.__drizzle_migrations;`,\n ),\n )\n \n rows = query.rows\n }\n\n } catch (e) {\n rows = []\n }\n\n if (rows && rows.length > 0) {\n existingMigrationHashes = rows.map((row) => row[0])\n }\n\n if (existingMigrationHashes) {\n let shouldRebuildDb = false\n for (const existingHash of existingMigrationHashes) {\n if (!incomingMigrationHashes.includes(existingHash)) {\n shouldRebuildDb = true\n break\n }\n }\n if (shouldRebuildDb) {\n await zenfs.promises.unlink(`${pathToDbDir}/${dbName}.sqlite3`)\n }\n }\n }\n\n await drizzleMigrate(\n drizzleDb,\n async (queriesToRun) => {\n // logger('queriesToRun', queriesToRun)\n for (const query of queriesToRun) {\n // logger('query', query)\n await drizzleDb.run(sql.raw(query))\n }\n },\n {\n migrationsFolder: pathToDbDir,\n },\n )\n } catch (error) {\n\n await BaseFileManager.waitForFile(`${pathToDbDir}/meta/_journal.json`)\n\n const journalExists = await BaseFileManager.pathExists(\n `${pathToDbDir}/meta/_journal.json`,\n )\n\n if (journalExists) {\n await this.migrate(pathToDbDir, dbName,)\n }\n\n if (!journalExists) {\n throw new Error('Failed to migrate database')\n }\n\n\n }\n\n this.appDb = drizzleDb\n // const createTempTableQuery = await appDb.run(\n // sql.raw(\n // `CREATE TEMP TABLE IF NOT EXISTS temp_last_inserted_id (id INTEGER, table TEXT);`,\n // ),\n // )\n //\n // logger(\n // '[db/actors] [migrate] createTempTableQuery',\n // createTempTableQuery,\n // )\n\n // const triggersQuery = await appDb.run(\n // sql.raw(\n // `SELECT name\n // FROM main.sqlite_master\n // WHERE type = 'trigger';`,\n // ),\n // )\n //\n // logger('[db/actors] [migrate] triggersQuery', triggersQuery)\n //\n // const triggers = triggersQuery.rows.map((row) => row[0])\n //\n // const tablesQuery = await appDb.run(\n // sql.raw(\n // `SELECT name\n // FROM main.sqlite_master\n // WHERE type = 'table';`,\n // ),\n // )\n //\n // logger('[db/actors] [migrate] tablesQuery', tablesQuery)\n //\n // const tableNames = tablesQuery.rows.map((row) => row[0])\n // logger('[db/actors] [migrate] tableNames', tableNames)\n // for (const tableName of tableNames) {\n // const triggerName = `after_insert_${tableName}`\n // if (triggers.includes(triggerName)) {\n // continue\n // }\n // const createTriggerQuery = await appDb.run(\n // sql.raw(\n // `CREATE TRIGGER after_insert_${tableName}\n // AFTER INSERT ON ${tableName}\n // BEGIN\n // DELETE FROM temp_last_inserted_id;\n // INSERT INTO temp_last_inserted_id (id) VALUES (new.id);\n // END;`,\n // ),\n // )\n //\n // logger(\n // '[db/actors] [migrate] createTriggerQuery',\n // createTriggerQuery,\n // )\n // }\n }\n\n static async exec(sql: string, params: any[]) {\n const rowsToReturnRaw: SqliteWasmResult[] = []\n const rowsValues: string[][] = []\n \n // For a single exec command, the callback potentially gets called several times -- once for each row.\n // So we need to collect all rows into a final array to return (execResult).\n const rowsToReturn = await new Promise((resolve, reject) => {\n\n\n this.sqliteWasmClient('exec', {\n dbId:this.dbId,\n sql,\n bind: params,\n callback: (result) => {\n // Checks if this is the final callback of the query\n if (!result || !result.row || !result.rowNumber) {\n const returnResult = []\n for (const currRow of rowsToReturnRaw) {\n returnResult.push(currRow.row)\n }\n resolve(returnResult)\n } else {\n // If not the final response, add this row to the return array\n rowsToReturnRaw.push(result)\n }\n },\n }).catch(async (error) => {\n reject(error)\n })\n })\n \n return rowsToReturn || []\n }\n}\n\nexport { Db }\n"],"names":["drizzleMigrate"],"mappings":";;;;;;;;;;AAUA,MAAM,MAAM,GAAG,KAAK,CAAC,uBAAuB,CAAC;AAG7C,MAAM,EAAG,SAAQ,MAAM,CAAA;AAQrB,IAAA,WAAA,GAAA;AACE,QAAA,KAAK,EAAE;;AAGT,IAAA,OAAO,QAAQ,GAAA;QACb,OAAO,IAAI,CAAC,KAAK;;AAGnB,IAAA,OAAO,YAAY,GAAA;AACjB,QAAA,OAAO,CAAC,CAAC,IAAI,CAAC,KAAK;;AAGrB,IAAA,aAAa,WAAW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AAE,MAAM,KAAI;AAG1D,YAAA,IAAI,CAAC,gBAAgB,CAAC,MAAM,EAAE;gBAC3B,IAAI,EAAC,IAAI,CAAC,IAAI;gBACd,GAAG;AACH,gBAAA,IAAI,EAAE,MAAM;AACZ,gBAAA,QAAQ,EAAE,CAAC,MAAM,KAAI;;AAEnB,oBAAA,IAAI,CAAC,MAAM,IAAI,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC,SAAS,EAAE;wBAC/C,MAAM,YAAY,GAAG,EAAE;AACvB,wBAAA,KAAK,MAAM,OAAO,IAAI,eAAe,EAAE;AACrC,4BAAA,YAAY,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC;;wBAEhC,OAAO,CAAC,YAAY,CAAC;;yBAChB;;AAEL,wBAAA,eAAe,CAAC,IAAI,CAAC,MAAM,CAAC;;iBAE/B;AACF,aAAA,CAAC,CAAC,KAAK,CAAC,OAAO,KAAK,KAAI;gBACvB,MAAM,CAAC,KAAK,CAAC;AACf,aAAC,CAAC;AACJ,SAAC,CAAC;QAEF,OAAO,YAAY,IAAI,EAAE;;AAE5B;;;;"}
|
|
@@ -20,6 +20,8 @@ declare class FileManager extends BaseFileManager {
|
|
|
20
20
|
static readFile(filePath: string): Promise<File>;
|
|
21
21
|
static readFileAsBuffer(filePath: string): Promise<Buffer>;
|
|
22
22
|
static readFileAsString(filePath: string): Promise<string>;
|
|
23
|
+
static getParentDirPath(filePath: string): string;
|
|
24
|
+
static getFilenameFromPath(filePath: string): string;
|
|
23
25
|
}
|
|
24
26
|
export { FileManager };
|
|
25
27
|
//# sourceMappingURL=FileManager.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"FileManager.d.ts","sourceRoot":"","sources":["../../../../src/browser/helpers/FileManager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAU,uCAAuC,CAAA;
|
|
1
|
+
{"version":3,"file":"FileManager.d.ts","sourceRoot":"","sources":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,GAAG,MAAM;IAIjD,MAAM,CAAC,mBAAmB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM;CAGrD;AAsDD,OAAO,EAAE,WAAW,EAAE,CAAA"}
|
|
@@ -2,6 +2,7 @@ import { BaseFileManager } from '../../helpers/FileManager/BaseFileManager.js';
|
|
|
2
2
|
import { FileDownloader } from '../workers/FileDownloader.js';
|
|
3
3
|
import { ImageResizer } from '../workers/ImageResizer.js';
|
|
4
4
|
import debug from 'debug';
|
|
5
|
+
import path from 'path-browserify';
|
|
5
6
|
|
|
6
7
|
const logger = debug('seedSdk:browser:helpers:FileManager');
|
|
7
8
|
class FileManager extends BaseFileManager {
|
|
@@ -101,8 +102,12 @@ class FileManager extends BaseFileManager {
|
|
|
101
102
|
* @returns {Promise<boolean>} - Resolves to true if the file exists within the timeout period, otherwise false.
|
|
102
103
|
*/
|
|
103
104
|
static async waitForFile(filePath, interval = 1000, timeout = 60000) {
|
|
104
|
-
const fs = await this.getFs()
|
|
105
|
-
const fsNode = await import('node:fs')
|
|
105
|
+
// const fs = await this.getFs()
|
|
106
|
+
// const fsNode = await import('node:fs')
|
|
107
|
+
const pathExists = await this.pathExists(filePath);
|
|
108
|
+
if (pathExists) {
|
|
109
|
+
return true;
|
|
110
|
+
}
|
|
106
111
|
return new Promise((resolve, reject) => {
|
|
107
112
|
const startTime = Date.now();
|
|
108
113
|
let isBusy = false;
|
|
@@ -112,11 +117,12 @@ class FileManager extends BaseFileManager {
|
|
|
112
117
|
return;
|
|
113
118
|
}
|
|
114
119
|
isBusy = true;
|
|
115
|
-
// TODO: Needs to read from OPFS
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
+
// // TODO: Needs to read from OPFS
|
|
121
|
+
// const exists = await BaseFileManager.pathExists(filePath)
|
|
122
|
+
// if (exists) {
|
|
123
|
+
// stop()
|
|
124
|
+
// resolve(true)
|
|
125
|
+
// }
|
|
120
126
|
const pathExists = await this.pathExists(filePath);
|
|
121
127
|
if (pathExists) {
|
|
122
128
|
stop();
|
|
@@ -256,6 +262,12 @@ class FileManager extends BaseFileManager {
|
|
|
256
262
|
const buffer = await this.readFileAsBuffer(filePath);
|
|
257
263
|
return buffer.toString('utf-8');
|
|
258
264
|
}
|
|
265
|
+
static getParentDirPath(filePath) {
|
|
266
|
+
return path.dirname(filePath);
|
|
267
|
+
}
|
|
268
|
+
static getFilenameFromPath(filePath) {
|
|
269
|
+
return path.basename(filePath);
|
|
270
|
+
}
|
|
259
271
|
}
|
|
260
272
|
class CancelableInterval {
|
|
261
273
|
constructor(task, interval) {
|
|
@@ -278,7 +290,7 @@ class CancelableInterval {
|
|
|
278
290
|
}
|
|
279
291
|
catch (error) {
|
|
280
292
|
if (error instanceof DOMException && error.name === 'AbortError') {
|
|
281
|
-
|
|
293
|
+
logger('Previous task was canceled.');
|
|
282
294
|
}
|
|
283
295
|
else {
|
|
284
296
|
console.error('Task error:', error);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"FileManager.js","sources":["../../../../../src/browser/helpers/FileManager.ts"],"sourcesContent":["import { BaseFileManager } from '@/helpers/FileManager/BaseFileManager'\nimport { FileDownloader } from '../workers/FileDownloader'\nimport { ImageResizer } from '../workers/ImageResizer'\nimport debug from 'debug'\n\nconst logger = debug('seedSdk:browser:helpers:FileManager')\n\nclass FileManager extends BaseFileManager {\n\n static async getFs() {\n const fs = await import('@zenfs/core')\n return fs\n }\n\n static async getContentUrlFromPath( path: string ): Promise<string | undefined> {\n\n const fileExists = await this.pathExists(path)\n if ( fileExists ) {\n const file = await this.readFile(path)\n return URL.createObjectURL(file)\n }\n }\n\n static async initializeFileSystem(): Promise<void> {\n\n const fs = await this.getFs()\n const {WebAccess} = await import('@zenfs/dom')\n const {configureSingle} = fs\n\n const handle = await navigator.storage.getDirectory()\n // await configure({\n // mounts: {\n // '/': {\n // backend: WebAccess,\n // handle,\n // },\n // },\n // disableUpdateOnRead: true,\n // onlySyncOnClose: true,\n // })\n await configureSingle({\n backend: WebAccess,\n handle,\n })\n }\n\n static async downloadAllFiles( {\n transactionIds,\n arweaveHost,\n excludedTransactions,\n }: DownloadAllFilesParams ): Promise<void> {\n const fileDownloader = new FileDownloader()\n await fileDownloader.downloadAll({ transactionIds, arweaveHost, excludedTransactions })\n }\n\n static async resizeImage( { filePath, width, height }: ResizeImageParams ): Promise<void> {\n const imageResizer = new ImageResizer()\n await imageResizer.resize({ filePath, width, height })\n }\n\n static async resizeAllImages( { width, height }: ResizeAllImagesParams ): Promise<void> {\n const imageResizer = new ImageResizer()\n await imageResizer.resizeAll({ width, height })\n }\n\n static async pathExists(filePath: string): Promise<boolean> {\n try {\n // Access the root directory of OPFS\n const root = await navigator.storage.getDirectory();\n \n // Split the path into segments\n const parts = filePath.split('/').filter(Boolean);\n let currentDir = root;\n\n // Traverse each part of the path\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i];\n try {\n const handle = await currentDir.getDirectoryHandle(part, { create: false });\n currentDir = handle; // Move into the directory\n } catch (error) {\n try {\n // If it's not a directory, check if it's a file\n await currentDir.getFileHandle(part, { create: false });\n // If we successfully got a file handle and it's the last part, return true\n return i === parts.length - 1;\n } catch {\n // Neither a directory nor a file exists\n return false;\n }\n }\n }\n\n return true; // Directory exists\n } catch (error) {\n return false; // Any error means the path does not exist\n }\n }\n\n static async createDirIfNotExists(filePath: string): Promise<void> {\n if (!(await this.pathExists(filePath))) {\n try {\n const fs = await this.getFs()\n await fs.promises.mkdir(filePath)\n } catch (error) {\n // This is a no-op. We tried to create a directory that already exists.\n logger('Attempted to create a directory that already exists')\n }\n }\n }\n\n /**\n * Waits for a file to exist at the specified path.\n * @param {string} filePath - The path of the file to check.\n * @param {number} interval - The interval in milliseconds between checks (default: 500ms).\n * @param {number} timeout - The timeout in milliseconds to wait for the file to exist (default: 10s).\n * @returns {Promise<boolean>} - Resolves to true if the file exists within the timeout period, otherwise false.\n */\n static async waitForFile(filePath: string, interval: number = 1000, timeout: number = 60000): Promise<boolean> {\n\n const fs = await this.getFs()\n const fsNode = await import('node:fs')\n\n return new Promise((resolve, reject) => {\n const startTime = Date.now()\n \n let isBusy = false\n\n const cancelableInterval = new CancelableInterval(async (stop) => {\n logger('waitForFile', filePath)\n if (isBusy) {\n return\n }\n isBusy = true\n // TODO: Needs to read from OPFS\n if (fs.existsSync(filePath) && fsNode.existsSync(filePath)) {\n stop()\n resolve(true)\n }\n\n const pathExists = await this.pathExists(filePath)\n if (pathExists) {\n stop()\n resolve(true)\n }\n\n if (Date.now() - startTime >= timeout) {\n stop()\n reject(new Error('Timeout exceeded while waiting for file'))\n }\n isBusy = false\n }, interval)\n\n cancelableInterval.start()\n \n // const _interval = setInterval(async () => {\n // logger('waitForFile', filePath)\n // if (isBusy) {\n // return\n // }\n // isBusy = true\n // // TODO: Needs to read from OPFS\n // if (fs.existsSync(filePath) && fsNode.existsSync(filePath)) {\n // clearInterval(_interval)\n // resolve(true)\n // }\n\n // const pathExists = await this.pathExists(filePath)\n // if (pathExists) {\n // clearInterval(_interval)\n // resolve(true)\n // }\n\n // if (Date.now() - startTime >= timeout) {\n // clearInterval(_interval)\n // reject(new Error('Timeout exceeded while waiting for file'))\n // }\n // isBusy = false\n // }, interval)\n \n // retry(\n // {\n // times: Math.ceil(timeout / interval),\n // interval: interval,\n // },\n // (callback: Function) => {\n // if (fs.existsSync(filePath) && fsNode.existsSync(filePath)) {\n // return callback(null, true) // File exists, finish with success\n // }\n // if (Date.now() - startTime >= timeout) {\n // return callback(new Error('Timeout exceeded while waiting for file'))\n // }\n // callback(new Error('File does not exist yet')) // Retry with this error\n // },\n // (err: Error, result: boolean) => {\n // if (err) {\n // return resolve(false) // Resolve as false if timeout or error occurs\n // }\n // resolve(result) // Resolve as true if file exists\n // },\n // )\n })\n }\n\n static async saveFile(filePath: string, content: string | Blob | ArrayBuffer): Promise<void> {\n try {\n // Get a handle to the OPFS root directory\n const root = await navigator.storage.getDirectory();\n \n // Split the file path into directory and file name\n const pathParts = filePath.split('/');\n const fileName = pathParts.pop();\n if (!fileName) throw new Error('Invalid file path');\n\n // Traverse directories and create them if they don't exist\n let currentDir = root;\n for (const part of pathParts) {\n if (part !== '') {\n currentDir = await currentDir.getDirectoryHandle(part, { create: true });\n }\n }\n\n // Get the file handle and create the file if it doesn't exist\n const fileHandle = await currentDir.getFileHandle(fileName, { create: true });\n\n // Create a writable stream and write the content\n const writable = await fileHandle.createWritable();\n \n if (typeof content === 'string' || content instanceof Uint8Array) {\n await writable.write(content);\n } else if (content instanceof Blob) {\n await writable.write(content);\n } else if (content instanceof ArrayBuffer) {\n await writable.write(new Blob([content]));\n } else {\n throw new Error('Unsupported content type');\n }\n\n await writable.close();\n logger(`File written successfully: ${filePath}`);\n } catch (error) {\n console.error(`Error writing to OPFS: ${error.message}`);\n }\n }\n\n static async readFile(filePath: string): Promise<File> {\n try {\n // Get a handle to the OPFS root directory\n const root = await navigator.storage.getDirectory();\n \n // Split the file path into directory and file name\n const pathParts = filePath.split('/');\n const fileName = pathParts.pop();\n if (!fileName) throw new Error('Invalid file path');\n \n // Traverse directories to reach the target file\n let currentDir = root;\n for (const part of pathParts) {\n if (part !== '') {\n currentDir = await currentDir.getDirectoryHandle(part, { create: false });\n }\n }\n \n // Get the file handle\n const fileHandle = await currentDir.getFileHandle(fileName, { create: false });\n \n // Get the file and read it as an ArrayBuffer\n return await fileHandle.getFile();\n } catch (error) {\n console.error(`Error reading from OPFS: ${error.message}`);\n throw error;\n }\n }\n\n static async readFileAsBuffer(filePath: string): Promise<Buffer> {\n try {\n\n // Get the file and read it as an ArrayBuffer\n const file = await this.readFile(filePath)\n const arrayBuffer = await file.arrayBuffer();\n\n // Convert ArrayBuffer to Buffer\n return Buffer.from(arrayBuffer);\n } catch (error) {\n console.error(`Error reading from OPFS: ${error.message}`);\n throw error;\n }\n }\n\n static async readFileAsString(filePath: string): Promise<string> {\n const buffer = await this.readFileAsBuffer(filePath)\n return buffer.toString('utf-8')\n }\n}\n\ntype AsyncTask = (stop: () => void) => Promise<void>\n\n\nclass CancelableInterval {\n private intervalId: number | null = null;\n private currentTaskAbortController: AbortController | null = null;\n\n constructor(private task: AsyncTask, private interval: number) {}\n\n start() {\n this.intervalId = window.setInterval(async () => {\n if (this.currentTaskAbortController) {\n // Cancel the previous running task\n this.currentTaskAbortController.abort();\n }\n\n // Create a new abort controller for the current task\n this.currentTaskAbortController = new AbortController();\n const signal = this.currentTaskAbortController.signal;\n\n try {\n await this.taskWithCancellation(signal);\n } catch (error) {\n if (error instanceof DOMException && error.name === 'AbortError') {\n console.log('Previous task was canceled.');\n } else {\n console.error('Task error:', error);\n }\n this.stop()\n }\n }, this.interval);\n }\n\n private async taskWithCancellation(signal: AbortSignal) {\n await this.task(() => this.stop())\n if (signal.aborted) {\n throw new DOMException('Task was aborted', 'AbortError');\n }\n }\n\n stop() {\n if (this.intervalId !== null) {\n clearInterval(this.intervalId);\n this.intervalId = null;\n }\n if (this.currentTaskAbortController) {\n this.currentTaskAbortController.abort();\n }\n }\n}\n\n\nexport { FileManager }\n"],"names":[],"mappings":";;;;;AAKA,MAAM,MAAM,GAAG,KAAK,CAAC,qCAAqC,CAAC;AAE3D,MAAM,WAAY,SAAQ,eAAe,CAAA;IAEvC,aAAa,KAAK,GAAA;AAChB,QAAA,MAAM,EAAE,GAAG,MAAM,OAAO,aAAa,CAAC;AACtC,QAAA,OAAO,EAAE;;AAGX,IAAA,aAAa,qBAAqB,CAAE,IAAY,EAAA;QAE9C,MAAM,UAAU,GAAG,MAAM,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC;QAC9C,IAAK,UAAU,EAAG;YAChB,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC;AACtC,YAAA,OAAO,GAAG,CAAC,eAAe,CAAC,IAAI,CAAC;;;IAIpC,aAAa,oBAAoB,GAAA;AAE/B,QAAA,MAAM,EAAE,GAAG,MAAM,IAAI,CAAC,KAAK,EAAE;QAC7B,MAAM,EAAC,SAAS,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AAC9B,YAAA,IAAI,CAAC,UAAU,GAAG,IAAI;;AAE1B,QAAA,IAAI,IAAI,CAAC,0BAA0B,EAAE;AACjC,YAAA,IAAI,CAAC,0BAA0B,CAAC,KAAK,EAAE;;;AAGlD;;;;"}
|
|
1
|
+
{"version":3,"file":"FileManager.js","sources":["../../../../../src/browser/helpers/FileManager.ts"],"sourcesContent":["import { BaseFileManager } from '@/helpers/FileManager/BaseFileManager'\nimport { FileDownloader } from '../workers/FileDownloader'\nimport { ImageResizer } from '../workers/ImageResizer'\nimport debug from 'debug'\nimport path from 'path-browserify'\n\nconst logger = debug('seedSdk:browser:helpers:FileManager')\n\nclass FileManager extends BaseFileManager {\n\n static async getFs() {\n const fs = await import('@zenfs/core')\n return fs\n }\n\n static async getContentUrlFromPath( path: string ): Promise<string | undefined> {\n\n const fileExists = await this.pathExists(path)\n if ( fileExists ) {\n const file = await this.readFile(path)\n return URL.createObjectURL(file)\n }\n }\n\n static async initializeFileSystem(): Promise<void> {\n\n const fs = await this.getFs()\n const {WebAccess} = await import('@zenfs/dom')\n const {configureSingle} = fs\n\n const handle = await navigator.storage.getDirectory()\n // await configure({\n // mounts: {\n // '/': {\n // backend: WebAccess,\n // handle,\n // },\n // },\n // disableUpdateOnRead: true,\n // onlySyncOnClose: true,\n // })\n await configureSingle({\n backend: WebAccess,\n handle,\n })\n }\n\n static async downloadAllFiles( {\n transactionIds,\n arweaveHost,\n excludedTransactions,\n }: DownloadAllFilesParams ): Promise<void> {\n const fileDownloader = new FileDownloader()\n await fileDownloader.downloadAll({ transactionIds, arweaveHost, excludedTransactions })\n }\n\n static async resizeImage( { filePath, width, height }: ResizeImageParams ): Promise<void> {\n const imageResizer = new ImageResizer()\n await imageResizer.resize({ filePath, width, height })\n }\n\n static async resizeAllImages( { width, height }: ResizeAllImagesParams ): Promise<void> {\n const imageResizer = new ImageResizer()\n await imageResizer.resizeAll({ width, height })\n }\n\n static async pathExists(filePath: string): Promise<boolean> {\n try {\n // Access the root directory of OPFS\n const root = await navigator.storage.getDirectory();\n \n // Split the path into segments\n const parts = filePath.split('/').filter(Boolean);\n let currentDir = root;\n\n // Traverse each part of the path\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i];\n try {\n const handle = await currentDir.getDirectoryHandle(part, { create: false });\n currentDir = handle; // Move into the directory\n } catch (error) {\n try {\n // If it's not a directory, check if it's a file\n await currentDir.getFileHandle(part, { create: false });\n // If we successfully got a file handle and it's the last part, return true\n return i === parts.length - 1;\n } catch {\n // Neither a directory nor a file exists\n return false;\n }\n }\n }\n\n return true; // Directory exists\n } catch (error) {\n return false; // Any error means the path does not exist\n }\n }\n\n static async createDirIfNotExists(filePath: string): Promise<void> {\n if (!(await this.pathExists(filePath))) {\n try {\n const fs = await this.getFs()\n await fs.promises.mkdir(filePath)\n } catch (error) {\n // This is a no-op. We tried to create a directory that already exists.\n logger('Attempted to create a directory that already exists')\n }\n }\n }\n\n /**\n * Waits for a file to exist at the specified path.\n * @param {string} filePath - The path of the file to check.\n * @param {number} interval - The interval in milliseconds between checks (default: 500ms).\n * @param {number} timeout - The timeout in milliseconds to wait for the file to exist (default: 10s).\n * @returns {Promise<boolean>} - Resolves to true if the file exists within the timeout period, otherwise false.\n */\n static async waitForFile(filePath: string, interval: number = 1000, timeout: number = 60000): Promise<boolean> {\n\n // const fs = await this.getFs()\n // const fsNode = await import('node:fs')\n const pathExists = await this.pathExists(filePath)\n\n if (pathExists) {\n return true\n }\n\n return new Promise((resolve, reject) => {\n const startTime = Date.now()\n\n let isBusy = false\n\n const cancelableInterval = new CancelableInterval(async (stop) => {\n logger('waitForFile', filePath)\n if (isBusy) {\n return\n }\n isBusy = true\n // // TODO: Needs to read from OPFS\n // const exists = await BaseFileManager.pathExists(filePath)\n // if (exists) {\n // stop()\n // resolve(true)\n // }\n\n const pathExists = await this.pathExists(filePath)\n if (pathExists) {\n stop()\n resolve(true)\n }\n\n if (Date.now() - startTime >= timeout) {\n stop()\n reject(new Error('Timeout exceeded while waiting for file'))\n }\n isBusy = false\n }, interval)\n\n cancelableInterval.start()\n \n // const _interval = setInterval(async () => {\n // logger('waitForFile', filePath)\n // if (isBusy) {\n // return\n // }\n // isBusy = true\n // // TODO: Needs to read from OPFS\n // if (fs.existsSync(filePath) && fsNode.existsSync(filePath)) {\n // clearInterval(_interval)\n // resolve(true)\n // }\n\n // const pathExists = await this.pathExists(filePath)\n // if (pathExists) {\n // clearInterval(_interval)\n // resolve(true)\n // }\n\n // if (Date.now() - startTime >= timeout) {\n // clearInterval(_interval)\n // reject(new Error('Timeout exceeded while waiting for file'))\n // }\n // isBusy = false\n // }, interval)\n \n // retry(\n // {\n // times: Math.ceil(timeout / interval),\n // interval: interval,\n // },\n // (callback: Function) => {\n // if (fs.existsSync(filePath) && fsNode.existsSync(filePath)) {\n // return callback(null, true) // File exists, finish with success\n // }\n // if (Date.now() - startTime >= timeout) {\n // return callback(new Error('Timeout exceeded while waiting for file'))\n // }\n // callback(new Error('File does not exist yet')) // Retry with this error\n // },\n // (err: Error, result: boolean) => {\n // if (err) {\n // return resolve(false) // Resolve as false if timeout or error occurs\n // }\n // resolve(result) // Resolve as true if file exists\n // },\n // )\n })\n }\n\n static async saveFile(filePath: string, content: string | Blob | ArrayBuffer): Promise<void> {\n try {\n // Get a handle to the OPFS root directory\n const root = await navigator.storage.getDirectory();\n \n // Split the file path into directory and file name\n const pathParts = filePath.split('/');\n const fileName = pathParts.pop();\n if (!fileName) throw new Error('Invalid file path');\n\n // Traverse directories and create them if they don't exist\n let currentDir = root;\n for (const part of pathParts) {\n if (part !== '') {\n currentDir = await currentDir.getDirectoryHandle(part, { create: true });\n }\n }\n\n // Get the file handle and create the file if it doesn't exist\n const fileHandle = await currentDir.getFileHandle(fileName, { create: true });\n\n // Create a writable stream and write the content\n const writable = await fileHandle.createWritable();\n \n if (typeof content === 'string' || content instanceof Uint8Array) {\n await writable.write(content);\n } else if (content instanceof Blob) {\n await writable.write(content);\n } else if (content instanceof ArrayBuffer) {\n await writable.write(new Blob([content]));\n } else {\n throw new Error('Unsupported content type');\n }\n\n await writable.close();\n logger(`File written successfully: ${filePath}`);\n } catch (error) {\n console.error(`Error writing to OPFS: ${error.message}`);\n }\n }\n\n static async readFile(filePath: string): Promise<File> {\n try {\n // Get a handle to the OPFS root directory\n const root = await navigator.storage.getDirectory();\n \n // Split the file path into directory and file name\n const pathParts = filePath.split('/');\n const fileName = pathParts.pop();\n if (!fileName) throw new Error('Invalid file path');\n \n // Traverse directories to reach the target file\n let currentDir = root;\n for (const part of pathParts) {\n if (part !== '') {\n currentDir = await currentDir.getDirectoryHandle(part, { create: false });\n }\n }\n \n // Get the file handle\n const fileHandle = await currentDir.getFileHandle(fileName, { create: false });\n \n // Get the file and read it as an ArrayBuffer\n return await fileHandle.getFile();\n } catch (error) {\n console.error(`Error reading from OPFS: ${error.message}`);\n throw error;\n }\n }\n\n static async readFileAsBuffer(filePath: string): Promise<Buffer> {\n try {\n\n // Get the file and read it as an ArrayBuffer\n const file = await this.readFile(filePath)\n const arrayBuffer = await file.arrayBuffer();\n\n // Convert ArrayBuffer to Buffer\n return Buffer.from(arrayBuffer);\n } catch (error) {\n console.error(`Error reading from OPFS: ${error.message}`);\n throw error;\n }\n }\n\n static async readFileAsString(filePath: string): Promise<string> {\n const buffer = await this.readFileAsBuffer(filePath)\n return buffer.toString('utf-8')\n }\n\n static getParentDirPath(filePath: string): string {\n return path.dirname(filePath)\n }\n\n static getFilenameFromPath(filePath: string): string {\n return path.basename(filePath)\n }\n}\n\ntype AsyncTask = (stop: () => void) => Promise<void>\n\n\nclass CancelableInterval {\n private intervalId: number | null = null;\n private currentTaskAbortController: AbortController | null = null;\n\n constructor(private task: AsyncTask, private interval: number) {}\n\n start() {\n this.intervalId = window.setInterval(async () => {\n if (this.currentTaskAbortController) {\n // Cancel the previous running task\n this.currentTaskAbortController.abort();\n }\n\n // Create a new abort controller for the current task\n this.currentTaskAbortController = new AbortController();\n const signal = this.currentTaskAbortController.signal;\n\n try {\n await this.taskWithCancellation(signal);\n } catch (error) {\n if (error instanceof DOMException && error.name === 'AbortError') {\n logger('Previous task was canceled.');\n } else {\n console.error('Task error:', error);\n }\n this.stop()\n }\n }, this.interval);\n }\n\n private async taskWithCancellation(signal: AbortSignal) {\n await this.task(() => this.stop())\n if (signal.aborted) {\n throw new DOMException('Task was aborted', 'AbortError');\n }\n }\n\n stop() {\n if (this.intervalId !== null) {\n clearInterval(this.intervalId);\n this.intervalId = null;\n }\n if (this.currentTaskAbortController) {\n this.currentTaskAbortController.abort();\n }\n }\n}\n\n\nexport { FileManager }\n"],"names":[],"mappings":";;;;;;AAMA,MAAM,MAAM,GAAG,KAAK,CAAC,qCAAqC,CAAC;AAE3D,MAAM,WAAY,SAAQ,eAAe,CAAA;IAEvC,aAAa,KAAK,GAAA;AAChB,QAAA,MAAM,EAAE,GAAG,MAAM,OAAO,aAAa,CAAC;AACtC,QAAA,OAAO,EAAE;;AAGX,IAAA,aAAa,qBAAqB,CAAE,IAAY,EAAA;QAE9C,MAAM,UAAU,GAAG,MAAM,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC;QAC9C,IAAK,UAAU,EAAG;YAChB,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC;AACtC,YAAA,OAAO,GAAG,CAAC,eAAe,CAAC,IAAI,CAAC;;;IAIpC,aAAa,oBAAoB,GAAA;AAE/B,QAAA,MAAM,EAAE,GAAG,MAAM,IAAI,CAAC,KAAK,EAAE;QAC7B,MAAM,EAAC,SAAS,EAAC,GAAG,MAAM,OAAO,YAAY,CAAC;AAC9C,QAAA,MAAM,EAAC,eAAe,EAAC,GAAG,EAAE;QAE5B,MAAM,MAAM,GAAG,MAAM,SAAS,CAAC,OAAO,CAAC,YAAY,EAAE;;;;;;;;;;;AAWrD,QAAA,MAAM,eAAe,CAAC;AACpB,YAAA,OAAO,EAAE,SAAS;YAClB,MAAM;AACP,SAAA,CAAC;;IAGJ,aAAa,gBAAgB,CAAE,EAC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cAAc,SAAS,CAAA;AACvB,cAAc,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/browser/index.ts"],"names":[],"mappings":"AAGA,cAAc,SAAS,CAAA;AACvB,cAAc,SAAS,CAAA;AACvB,cAAc,QAAQ,CAAA;AACtB,cAAc,gBAAgB,CAAA"}
|
|
@@ -2,5 +2,6 @@ export * from './item';
|
|
|
2
2
|
export * from './property';
|
|
3
3
|
export * from './services';
|
|
4
4
|
export * from './db';
|
|
5
|
-
export { useDeleteItem } from '
|
|
5
|
+
export { useDeleteItem } from './trash';
|
|
6
|
+
export { useModels } from './model';
|
|
6
7
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/browser/react/index.ts"],"names":[],"mappings":"AAAA,cAAc,QAAQ,CAAA;AACtB,cAAc,YAAY,CAAA;AAC1B,cAAc,YAAY,CAAA;AAC1B,cAAc,MAAM,CAAA;AACpB,OAAO,EAAE,aAAa,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/browser/react/index.ts"],"names":[],"mappings":"AAAA,cAAc,QAAQ,CAAA;AACtB,cAAc,YAAY,CAAA;AAC1B,cAAc,YAAY,CAAA;AAC1B,cAAc,MAAM,CAAA;AACpB,OAAO,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA;AACvC,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAA"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"model.d.ts","sourceRoot":"","sources":["../../../../src/browser/react/model.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAExC,eAAO,MAAM,SAAS;;;;CAgBrB,CAAA"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { useState } from 'react';
|
|
2
|
+
import { useSelector } from '@xstate/react';
|
|
3
|
+
import { getGlobalService } from '../../services/global/globalMachine.js';
|
|
4
|
+
|
|
5
|
+
const useModels = () => {
|
|
6
|
+
const [_models, setModels] = useState();
|
|
7
|
+
const globalService = getGlobalService();
|
|
8
|
+
const models = useSelector(globalService, (snapshot) => {
|
|
9
|
+
if (snapshot && snapshot.context && snapshot.context.models) {
|
|
10
|
+
return snapshot.context.models;
|
|
11
|
+
}
|
|
12
|
+
return;
|
|
13
|
+
});
|
|
14
|
+
return {
|
|
15
|
+
models,
|
|
16
|
+
};
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
export { useModels };
|
|
20
|
+
//# sourceMappingURL=model.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"model.js","sources":["../../../../../src/browser/react/model.ts"],"sourcesContent":["import { useState } from 'react'\nimport { useSelector } from '@xstate/react'\nimport { getGlobalService } from '@/services/global/globalMachine'\nimport { ModelClassType } from '@/types'\n\nexport const useModels = () => {\n\n const [_models, setModels] = useState<{ [key: string]: ModelClassType } | undefined>()\n\n const globalService = getGlobalService()\n\n const models = useSelector(globalService, (snapshot) => {\n if (snapshot && snapshot.context && snapshot.context.models) {\n return snapshot.context.models\n }\n return\n })\n\n return {\n models,\n }\n}\n"],"names":[],"mappings":";;;;AAKO,MAAM,SAAS,GAAG,MAAK;IAE5B,MAAM,CAAC,OAAO,EAAE,SAAS,CAAC,GAAG,QAAQ,EAAiD;AAEtF,IAAA,MAAM,aAAa,GAAG,gBAAgB,EAAE;IAExC,MAAM,MAAM,GAAG,WAAW,CAAC,aAAa,EAAE,CAAC,QAAQ,KAAI;AACrD,QAAA,IAAI,QAAQ,IAAI,QAAQ,CAAC,OAAO,IAAI,QAAQ,CAAC,OAAO,CAAC,MAAM,EAAE;AAC3D,YAAA,OAAO,QAAQ,CAAC,OAAO,CAAC,MAAM;;QAEhC;AACF,KAAC,CAAC;IAEF,OAAO;QACL,MAAM;KACP;AACH;;;;"}
|
|
@@ -176,7 +176,7 @@ const usePersistedSnapshots = () => {
|
|
|
176
176
|
}
|
|
177
177
|
const initialize = async () => {
|
|
178
178
|
const persistedSnapshots = await load();
|
|
179
|
-
|
|
179
|
+
logger('persistedSnapshots:', persistedSnapshots);
|
|
180
180
|
setInitialized(true);
|
|
181
181
|
};
|
|
182
182
|
initialize();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"services.js","sources":["../../../../../src/browser/react/services.ts"],"sourcesContent":["import { useCallback, useEffect, useState } from 'react'\nimport { ActorRef, InspectedEventEvent } from 'xstate'\nimport { orderBy } from 'lodash-es'\nimport { produce } from 'immer'\nimport { eventEmitter } from '@/eventBus'\nimport pluralize from 'pluralize'\nimport { getGlobalService } from '@/services/global/globalMachine'\nimport { useSelector } from '@xstate/react'\nimport debug from 'debug'\nimport { appState } from '@/seedSchema'\nimport { like } from 'drizzle-orm'\nimport { BaseDb } from '@/db/Db/BaseDb'\nimport { MachineIds } from '@/services/internal/constants'\n\nconst logger = debug('seedSdk:react:services')\n\nconst finalStrings = ['idle', 'ready', 'done', 'success', 'initialized']\n\nexport const getServiceName = (service: ActorRef<any, any>) => {\n let name = 'actor'\n if (service && service.uniqueKey) {\n name = service.uniqueKey\n }\n if (service && !service.uniqueKey && service.logic && service.logic.config) {\n name = getServiceUniqueKey(service)\n }\n return name\n}\n\nexport const getServiceValue = (\n service: ActorRef<any, any>,\n): string | undefined => {\n let value\n if (service && service.getSnapshot() && service.getSnapshot().value) {\n value = service.getSnapshot().value\n }\n if (getServiceName(service) === 'global') {\n if (\n value &&\n typeof value === 'object' &&\n Object.keys(value).length > 0 &&\n Object.keys(value)[0] === 'initialized'\n ) {\n value = 'ready'\n }\n }\n if (value && typeof value === 'object') {\n value = JSON.stringify(value)\n }\n return value\n}\n\nexport const getServiceUniqueKey = (service: ActorRef<any, any>) => {\n if (!service || !service.logic || !service.logic.config || !service._snapshot) {\n return\n }\n const config = service.logic.config\n if (!config.id) {\n return\n }\n let uniqueKey = config.id\n if (config.id.includes('@seedSdk/')) {\n uniqueKey = config.id.match(/^.*@seedSdk\\/(\\w+)[\\.\\w]*/)[1]\n }\n let snapshot\n try {\n snapshot = service.getSnapshot()\n } catch (error) {\n logger('Error:', error)\n return uniqueKey\n }\n if (snapshot) {\n const context = snapshot.context\n if (context && context.dbName) {\n uniqueKey = context.dbName\n }\n if (context && context.modelNamePlural) {\n uniqueKey = context.modelNamePlural\n }\n if (context && context.modelName) {\n uniqueKey = pluralize(context.modelName.toLowerCase())\n }\n }\n return uniqueKey\n}\n\nexport const useService = (service: ActorRef<any, any>) => {\n const [timeElapsed, setTimeElapsed] = useState(0)\n\n const getPercentComplete = (service: ActorRef<any, any>) => {\n let percentComplete = 0\n if (service.logic.states) {\n const stateNames = []\n const startupStates = []\n\n for (const [stateName, state] of Object.entries(service.logic.states)) {\n if (state.tags.includes('loading')) {\n stateNames.push(stateName)\n startupStates.push(state)\n }\n }\n\n const totalStates = startupStates.length\n const value = getServiceValue(service)\n if (finalStrings.includes(value)) {\n return 0\n }\n const stateIndex = stateNames.indexOf(value)\n percentComplete = (stateIndex / totalStates) * 100\n }\n return percentComplete\n }\n\n const updateTime = useCallback(\n (interval) => {\n const context = service.getSnapshot().context\n const status = service.getSnapshot().value\n if (\n status === 'done' ||\n status === 'success' ||\n status === 'idle' ||\n status === 'ready'\n ) {\n clearInterval(interval)\n return\n }\n setTimeElapsed((timeElapsed) => timeElapsed + 1)\n },\n [service],\n )\n\n const startInterval = useCallback(() => {\n const interval = setInterval(() => {\n updateTime(interval)\n }, 1000)\n return interval\n }, [updateTime, service])\n\n useEffect(() => {\n const interval = startInterval()\n return () => clearInterval(interval)\n }, [])\n\n return {\n name: getServiceName(service),\n timeElapsed,\n value: getServiceValue(service),\n percentComplete: getPercentComplete(service),\n uniqueKey: getServiceUniqueKey(service),\n }\n}\n\nexport const useIsDbReady = () => {\n const [isDbReady, setIsDbReady] = useState(false)\n\n const { internalStatus } = useGlobalServiceStatus()\n\n useEffect(() => {\n if (internalStatus === 'ready') {\n setIsDbReady(true)\n }\n }, [internalStatus])\n\n return isDbReady\n}\n\nexport const usePersistedSnapshots = () => {\n const [initialized, setInitialized] = useState(false)\n\n const hasSavedSnapshots = useHasSavedSnapshots()\n\n const { services, percentComplete } = useServices()\n\n // Helper function to save all actor snapshots to the database\n const save = useCallback(async () => {\n for (const actor of services) {\n const uniqueKey = getServiceUniqueKey(actor)\n logger(\n `would save to db with snapshot__${uniqueKey}:`,\n JSON.stringify(actor.getPersistedSnapshot()),\n )\n // await writeAppState(\n // `snapshot__${uniqueKey}`,\n // JSON.stringify(actor.getPersistedSnapshot()),\n // )\n }\n }, [services])\n\n // Helper function to load persisted snapshots from the database\n const load = useCallback(async () => {\n const appDb = BaseDb.getAppDb()\n\n if (!appDb) {\n return []\n }\n\n const persistedSnapshots = await appDb\n .select()\n .from(appState)\n .where(like(appState.key, 'snapshot__%'))\n return persistedSnapshots\n }, [])\n\n useEffect(() => {\n if (!hasSavedSnapshots || initialized) {\n return\n }\n const initialize = async () => {\n const persistedSnapshots = await load()\n console.log('persistedSnapshots:', persistedSnapshots)\n setInitialized(true)\n }\n\n initialize()\n\n return () => {\n save() // Save snapshots on unmount\n }\n }, [hasSavedSnapshots, initialized])\n}\n\nexport const useHasSavedSnapshots = () => {\n const [hasSavedSnapshots, setHasSavedSnapshots] = useState(false)\n\n const isDbReady = useIsDbReady()\n\n useEffect(() => {\n if (isDbReady) {\n const _checkForSnapshots = async (): Promise<void> => {\n const appDb = BaseDb.getAppDb()\n\n const rows = await appDb\n .select()\n .from(appState)\n .where(like(appState.key, 'snapshot__%'))\n\n if (rows && rows.length > 0) {\n setHasSavedSnapshots(true)\n }\n }\n\n _checkForSnapshots()\n }\n }, [isDbReady])\n\n return hasSavedSnapshots\n}\n\nexport const useServices = () => {\n const [actors, setActors] = useState<ActorRef<any, any>[]>([])\n const [percentComplete, setPercentComplete] = useState(5)\n\n const actorsMap = new Map<string, ActorRef<any, any>>()\n\n useEffect(() => {\n const globalServiceListener = (eventObj: InspectedEventEvent) => {\n if (eventObj && eventObj.event && eventObj.event.type === 'init') {\n return\n }\n if (\n !eventObj || \n !eventObj.actorRef || \n !eventObj.actorRef.logic || \n !eventObj.actorRef.logic.config ||\n !eventObj.actorRef._snapshot\n ) {\n return\n }\n \n const service = eventObj.actorRef\n const services = [service]\n\n if (service.logic.config.id === MachineIds.GLOBAL) {\n const context = service.getSnapshot().context\n const keys = Object.keys(context)\n for (const key of keys) {\n if (!key.startsWith('internal') && key.endsWith('Service')) {\n const allItemsService = context[key]\n services.push(allItemsService)\n }\n }\n }\n\n services.forEach((innerService) => {\n const uniqueKey = getServiceUniqueKey(innerService)\n if (!uniqueKey) {\n return\n }\n innerService.uniqueKey = uniqueKey\n actorsMap.set(uniqueKey, innerService)\n })\n\n let actorsArray = Array.from(actorsMap.values())\n actorsArray = orderBy(actorsArray, (a) => a.logic.config.id, ['asc'])\n\n setActors(\n produce(actors, (draft) => {\n return actorsArray\n }),\n )\n }\n\n eventEmitter.addListener('inspect.globalService', globalServiceListener)\n\n return () => {\n eventEmitter.removeListener(\n 'inspect.globalService',\n globalServiceListener,\n )\n }\n }, [])\n\n useEffect(() => {\n const globalService = actors.find(\n (actor) => getServiceName(actor) === 'global',\n )\n const internalService = actors.find(\n (actor) => getServiceName(actor) === 'internal',\n )\n if (!globalService || !internalService) {\n return\n }\n if (\n getServiceValue(globalService) === 'initialized' &&\n getServiceValue(internalService) === 'ready'\n ) {\n const denominator = actors.length\n const finishedActors = actors.filter((actor) => {\n const value = getServiceValue(actor)\n return finalStrings.includes(value)\n })\n const numerator = finishedActors.length\n const percentComplete = (numerator / denominator) * 100\n setPercentComplete(percentComplete)\n }\n }, [actors])\n\n return {\n services: actors,\n percentComplete,\n }\n}\n\nexport const useGlobalServiceStatus = () => {\n const globalService = getGlobalService()\n\n const status = useSelector(globalService, (snapshot) => {\n return snapshot.value\n })\n\n const internalStatus = useSelector(\n globalService.getSnapshot().context.internalService,\n (snapshot) => {\n if (!snapshot) {\n return\n }\n return snapshot.value\n },\n )\n\n const internalService = useSelector(globalService, (snapshot) => {\n return snapshot.context.internalService\n })\n\n return {\n status,\n internalStatus,\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAcA,MAAM,MAAM,GAAG,KAAK,CAAC,wBAAwB,CAAC;AAE9C,MAAM,YAAY,GAAG,CAAC,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,aAAa,CAAC;AAE3D,MAAA,cAAc,GAAG,CAAC,OAA2B,KAAI;IAC5D,IAAI,IAAI,GAAG,OAAO;AAClB,IAAA,IAAI,OAAO,IAAI,OAAO,CAAC,SAAS,EAAE;AAChC,QAAA,IAAI,GAAG,OAAO,CAAC,SAAS;;AAE1B,IAAA,IAAI,OAAO,IAAI,CAAC,OAAO,CAAC,SAAS,IAAI,OAAO,CAAC,KAAK,IAAI,OAAO,CAAC,KAAK,CAAC,MAAM,EAAE;AAC1E,QAAA,IAAI,GAAG,mBAAmB,CAAC,OAAO,CAAC;;AAErC,IAAA,OAAO,IAAI;AACb;AAEa,MAAA,eAAe,GAAG,CAC7B,OAA2B,KACL;AACtB,IAAA,IAAI,KAAK;AACT,IAAA,IAAI,OAAO,IAAI,OAAO,CAAC,WAAW,EAAE,IAAI,OAAO,CAAC,WAAW,EAAE,CAAC,KAAK,EAAE;AACnE,QAAA,KAAK,GAAG,OAAO,CAAC,WAAW,EAAE,CAAC,KAAK;;AAErC,IAAA,IAAI,cAAc,CAAC,OAAO,CAAC,KAAK,QAAQ,EAAE;AACxC,QAAA,IACE,KAAK;YACL,OAAO,KAAK,KAAK,QAAQ;YACzB,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,MAAM,GAAG,CAAC;YAC7B,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,aAAa,EACvC;YACA,KAAK,GAAG,OAAO;;;AAGnB,IAAA,IAAI,KAAK,IAAI,OAAO,KAAK,KAAK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Aa,EAAE,CAAC,QAAQ,KAAI;QACrD,OAAO,QAAQ,CAAC,KAAK;AACvB,KAAC,CAAC;AAEF,IAAA,MAAM,cAAc,GAAG,WAAW,CAChC,aAAa,CAAC,WAAW,EAAE,CAAC,OAAO,CAAC,eAAe,EACnD,CAAC,QAAQ,KAAI;QACX,IAAI,CAAC,QAAQ,EAAE;YACb;;QAEF,OAAO,QAAQ,CAAC,KAAK;AACvB,KAAC,CACF;IAEuB,WAAW,CAAC,aAAa,EAAE,CAAC,QAAQ,KAAI;AAC9D,QAAA,OAAO,QAAQ,CAAC,OAAO,CAAC,eAAe;AACzC,KAAC;IAED,OAAO;QACL,MAAM;QACN,cAAc;KACf;AACH;;;;"}
|
|
1
|
+
{"version":3,"file":"services.js","sources":["../../../../../src/browser/react/services.ts"],"sourcesContent":["import { useCallback, useEffect, useState } from 'react'\nimport { ActorRef, InspectedEventEvent } from 'xstate'\nimport { orderBy } from 'lodash-es'\nimport { produce } from 'immer'\nimport { eventEmitter } from '@/eventBus'\nimport pluralize from 'pluralize'\nimport { getGlobalService } from '@/services/global/globalMachine'\nimport { useSelector } from '@xstate/react'\nimport debug from 'debug'\nimport { appState } from '@/seedSchema'\nimport { like } from 'drizzle-orm'\nimport { BaseDb } from '@/db/Db/BaseDb'\nimport { MachineIds } from '@/services/internal/constants'\n\nconst logger = debug('seedSdk:react:services')\n\nconst finalStrings = ['idle', 'ready', 'done', 'success', 'initialized']\n\nexport const getServiceName = (service: ActorRef<any, any>) => {\n let name = 'actor'\n if (service && service.uniqueKey) {\n name = service.uniqueKey\n }\n if (service && !service.uniqueKey && service.logic && service.logic.config) {\n name = getServiceUniqueKey(service)\n }\n return name\n}\n\nexport const getServiceValue = (\n service: ActorRef<any, any>,\n): string | undefined => {\n let value\n if (service && service.getSnapshot() && service.getSnapshot().value) {\n value = service.getSnapshot().value\n }\n if (getServiceName(service) === 'global') {\n if (\n value &&\n typeof value === 'object' &&\n Object.keys(value).length > 0 &&\n Object.keys(value)[0] === 'initialized'\n ) {\n value = 'ready'\n }\n }\n if (value && typeof value === 'object') {\n value = JSON.stringify(value)\n }\n return value\n}\n\nexport const getServiceUniqueKey = (service: ActorRef<any, any>) => {\n if (!service || !service.logic || !service.logic.config || !service._snapshot) {\n return\n }\n const config = service.logic.config\n if (!config.id) {\n return\n }\n let uniqueKey = config.id\n if (config.id.includes('@seedSdk/')) {\n uniqueKey = config.id.match(/^.*@seedSdk\\/(\\w+)[\\.\\w]*/)[1]\n }\n let snapshot\n try {\n snapshot = service.getSnapshot()\n } catch (error) {\n logger('Error:', error)\n return uniqueKey\n }\n if (snapshot) {\n const context = snapshot.context\n if (context && context.dbName) {\n uniqueKey = context.dbName\n }\n if (context && context.modelNamePlural) {\n uniqueKey = context.modelNamePlural\n }\n if (context && context.modelName) {\n uniqueKey = pluralize(context.modelName.toLowerCase())\n }\n }\n return uniqueKey\n}\n\nexport const useService = (service: ActorRef<any, any>) => {\n const [timeElapsed, setTimeElapsed] = useState(0)\n\n const getPercentComplete = (service: ActorRef<any, any>) => {\n let percentComplete = 0\n if (service.logic.states) {\n const stateNames = []\n const startupStates = []\n\n for (const [stateName, state] of Object.entries(service.logic.states)) {\n if (state.tags.includes('loading')) {\n stateNames.push(stateName)\n startupStates.push(state)\n }\n }\n\n const totalStates = startupStates.length\n const value = getServiceValue(service)\n if (finalStrings.includes(value)) {\n return 0\n }\n const stateIndex = stateNames.indexOf(value)\n percentComplete = (stateIndex / totalStates) * 100\n }\n return percentComplete\n }\n\n const updateTime = useCallback(\n (interval) => {\n const context = service.getSnapshot().context\n const status = service.getSnapshot().value\n if (\n status === 'done' ||\n status === 'success' ||\n status === 'idle' ||\n status === 'ready'\n ) {\n clearInterval(interval)\n return\n }\n setTimeElapsed((timeElapsed) => timeElapsed + 1)\n },\n [service],\n )\n\n const startInterval = useCallback(() => {\n const interval = setInterval(() => {\n updateTime(interval)\n }, 1000)\n return interval\n }, [updateTime, service])\n\n useEffect(() => {\n const interval = startInterval()\n return () => clearInterval(interval)\n }, [])\n\n return {\n name: getServiceName(service),\n timeElapsed,\n value: getServiceValue(service),\n percentComplete: getPercentComplete(service),\n uniqueKey: getServiceUniqueKey(service),\n }\n}\n\nexport const useIsDbReady = () => {\n const [isDbReady, setIsDbReady] = useState(false)\n\n const { internalStatus } = useGlobalServiceStatus()\n\n useEffect(() => {\n if (internalStatus === 'ready') {\n setIsDbReady(true)\n }\n }, [internalStatus])\n\n return isDbReady\n}\n\nexport const usePersistedSnapshots = () => {\n const [initialized, setInitialized] = useState(false)\n\n const hasSavedSnapshots = useHasSavedSnapshots()\n\n const { services, percentComplete } = useServices()\n\n // Helper function to save all actor snapshots to the database\n const save = useCallback(async () => {\n for (const actor of services) {\n const uniqueKey = getServiceUniqueKey(actor)\n logger(\n `would save to db with snapshot__${uniqueKey}:`,\n JSON.stringify(actor.getPersistedSnapshot()),\n )\n // await writeAppState(\n // `snapshot__${uniqueKey}`,\n // JSON.stringify(actor.getPersistedSnapshot()),\n // )\n }\n }, [services])\n\n // Helper function to load persisted snapshots from the database\n const load = useCallback(async () => {\n const appDb = BaseDb.getAppDb()\n\n if (!appDb) {\n return []\n }\n\n const persistedSnapshots = await appDb\n .select()\n .from(appState)\n .where(like(appState.key, 'snapshot__%'))\n return persistedSnapshots\n }, [])\n\n useEffect(() => {\n if (!hasSavedSnapshots || initialized) {\n return\n }\n const initialize = async () => {\n const persistedSnapshots = await load()\n logger('persistedSnapshots:', persistedSnapshots)\n setInitialized(true)\n }\n\n initialize()\n\n return () => {\n save() // Save snapshots on unmount\n }\n }, [hasSavedSnapshots, initialized])\n}\n\nexport const useHasSavedSnapshots = () => {\n const [hasSavedSnapshots, setHasSavedSnapshots] = useState(false)\n\n const isDbReady = useIsDbReady()\n\n useEffect(() => {\n if (isDbReady) {\n const _checkForSnapshots = async (): Promise<void> => {\n const appDb = BaseDb.getAppDb()\n\n const rows = await appDb\n .select()\n .from(appState)\n .where(like(appState.key, 'snapshot__%'))\n\n if (rows && rows.length > 0) {\n setHasSavedSnapshots(true)\n }\n }\n\n _checkForSnapshots()\n }\n }, [isDbReady])\n\n return hasSavedSnapshots\n}\n\nexport const useServices = () => {\n const [actors, setActors] = useState<ActorRef<any, any>[]>([])\n const [percentComplete, setPercentComplete] = useState(5)\n\n const actorsMap = new Map<string, ActorRef<any, any>>()\n\n useEffect(() => {\n const globalServiceListener = (eventObj: InspectedEventEvent) => {\n if (eventObj && eventObj.event && eventObj.event.type === 'init') {\n return\n }\n if (\n !eventObj || \n !eventObj.actorRef || \n !eventObj.actorRef.logic || \n !eventObj.actorRef.logic.config ||\n !eventObj.actorRef._snapshot\n ) {\n return\n }\n \n const service = eventObj.actorRef\n const services = [service]\n\n if (service.logic.config.id === MachineIds.GLOBAL) {\n const context = service.getSnapshot().context\n const keys = Object.keys(context)\n for (const key of keys) {\n if (!key.startsWith('internal') && key.endsWith('Service')) {\n const allItemsService = context[key]\n services.push(allItemsService)\n }\n }\n }\n\n services.forEach((innerService) => {\n const uniqueKey = getServiceUniqueKey(innerService)\n if (!uniqueKey) {\n return\n }\n innerService.uniqueKey = uniqueKey\n actorsMap.set(uniqueKey, innerService)\n })\n\n let actorsArray = Array.from(actorsMap.values())\n actorsArray = orderBy(actorsArray, (a) => a.logic.config.id, ['asc'])\n\n setActors(\n produce(actors, (draft) => {\n return actorsArray\n }),\n )\n }\n\n eventEmitter.addListener('inspect.globalService', globalServiceListener)\n\n return () => {\n eventEmitter.removeListener(\n 'inspect.globalService',\n globalServiceListener,\n )\n }\n }, [])\n\n useEffect(() => {\n const globalService = actors.find(\n (actor) => getServiceName(actor) === 'global',\n )\n const internalService = actors.find(\n (actor) => getServiceName(actor) === 'internal',\n )\n if (!globalService || !internalService) {\n return\n }\n if (\n getServiceValue(globalService) === 'initialized' &&\n getServiceValue(internalService) === 'ready'\n ) {\n const denominator = actors.length\n const finishedActors = actors.filter((actor) => {\n const value = getServiceValue(actor)\n return finalStrings.includes(value)\n })\n const numerator = finishedActors.length\n const percentComplete = (numerator / denominator) * 100\n setPercentComplete(percentComplete)\n }\n }, [actors])\n\n return {\n services: actors,\n percentComplete,\n }\n}\n\nexport const useGlobalServiceStatus = () => {\n const globalService = getGlobalService()\n\n const status = useSelector(globalService, (snapshot) => {\n return snapshot.value\n })\n\n const internalStatus = useSelector(\n globalService.getSnapshot().context.internalService,\n (snapshot) => {\n if (!snapshot) {\n return\n }\n return snapshot.value\n },\n )\n\n const internalService = useSelector(globalService, (snapshot) => {\n return snapshot.context.internalService\n })\n\n return {\n status,\n internalStatus,\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAcA,MAAM,MAAM,GAAG,KAAK,CAAC,wBAAwB,CAAC;AAE9C,MAAM,YAAY,GAAG,CAAC,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,aAAa,CAAC;AAE3D,MAAA,cAAc,GAAG,CAAC,OAA2B,KAAI;IAC5D,IAAI,IAAI,GAAG,OAAO;AAClB,IAAA,IAAI,OAAO,IAAI,OAAO,CAAC,SAAS,EAAE;AAChC,QAAA,IAAI,GAAG,OAAO,CAAC,SAAS;;AAE1B,IAAA,IAAI,OAAO,IAAI,CAAC,OAAO,CAAC,SAAS,IAAI,OAAO,CAAC,KAAK,IAAI,OAAO,CAAC,KAAK,CAAC,MAAM,EAAE;AAC1E,QAAA,IAAI,GAAG,mBAAmB,CAAC,OAAO,CAAC;;AAErC,IAAA,OAAO,IAAI;AACb;AAEa,MAAA,eAAe,GAAG,CAC7B,OAA2B,KACL;AACtB,IAAA,IAAI,KAAK;AACT,IAAA,IAAI,OAAO,IAAI,OAAO,CAAC,WAAW,EAAE,IAAI,OAAO,CAAC,WAAW,EAAE,CAAC,KAAK,EAAE;AACnE,QAAA,KAAK,GAAG,OAAO,CAAC,WAAW,EAAE,CAAC,KAAK;;AAErC,IAAA,IAAI,cAAc,CAAC,OAAO,CAAC,KAAK,QAAQ,EAAE;AACxC,QAAA,IACE,KAAK;YACL,OAAO,KAAK,KAAK,QAAQ;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,CAAC,MAAM,CAAC,CAAC;IAEZ,OAAO;AACL,QAAA,QAAQ,EAAE,MAAM;QAChB,eAAe;KAChB;AACH;AAEO,MAAM,sBAAsB,GAAG,MAAK;AACzC,IAAA,MAAM,aAAa,GAAG,gBAAgB,EAAE;IAExC,MAAM,MAAM,GAAG,WAAW,CAAC,aAAa,EAAE,CAAC,QAAQ,KAAI;QACrD,OAAO,QAAQ,CAAC,KAAK;AACvB,KAAC,CAAC;AAEF,IAAA,MAAM,cAAc,GAAG,WAAW,CAChC,aAAa,CAAC,WAAW,EAAE,CAAC,OAAO,CAAC,eAAe,EACnD,CAAC,QAAQ,KAAI;QACX,IAAI,CAAC,QAAQ,EAAE;YACb;;QAEF,OAAO,QAAQ,CAAC,KAAK;AACvB,KAAC,CACF;IAEuB,WAAW,CAAC,aAAa,EAAE,CAAC,QAAQ,KAAI;AAC9D,QAAA,OAAO,QAAQ,CAAC,OAAO,CAAC,eAAe;AACzC,KAAC;IAED,OAAO;QACL,MAAM;QACN,cAAc;KACf;AACH;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"FileDownloader.d.ts","sourceRoot":"","sources":["../../../../src/browser/workers/FileDownloader.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"FileDownloader.d.ts","sourceRoot":"","sources":["../../../../src/browser/workers/FileDownloader.ts"],"names":[],"mappings":"AAMA,qBAAa,cAAc;IACzB,OAAO,CAAC,KAAK,CAAQ;IACrB,OAAO,CAAC,cAAc,CAAe;IACrC,OAAO,CAAC,aAAa,CAAQ;;IAUtB,WAAW,0DAA+D,sBAAsB,KAAG,OAAO,CAAC,IAAI,CAAC,CA2CtH;CACF"}
|