@univerjs-pro/collaboration-history-database-sqlite 1.4.0 → 1.6.0

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/index.cjs CHANGED
@@ -1,4 +1,9 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let c=require("libsql");c=s(c,1);let l=require("node:fs");var u=`history`,d=`
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,s)=>(s=n==null?{}:e(i(n)),o(r||!n||!n.__esModule||!a.call(n,`default`)?t(s,`default`,{value:n,enumerable:!0}):s,n));let c=require("libsql");c=s(c,1);let l=require("node:fs");var u=`history`,d=`
2
+ CREATE TABLE IF NOT EXISTS collaboration_schema_versions (
3
+ component TEXT PRIMARY KEY,
4
+ version INTEGER NOT NULL CHECK (version >= 1)
5
+ );
6
+ `,f=`
2
7
  CREATE TABLE collaboration_history_records (
3
8
  unit_id TEXT NOT NULL,
4
9
  start_revision INTEGER NOT NULL CHECK (start_revision >= 1),
@@ -8,12 +13,12 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
8
13
  additional_fields TEXT,
9
14
  PRIMARY KEY (unit_id, start_revision)
10
15
  );
11
- `,f=`
16
+ `,p=`
12
17
  CREATE INDEX collaboration_history_origin_lookup
13
18
  ON collaboration_history_records(unit_id, origin, start_revision);
14
19
  CREATE INDEX collaboration_history_creator_lookup
15
20
  ON collaboration_history_records(unit_id, user_id, start_revision);
16
- `,p=class{_database;_disposed=!1;constructor(e){if(!e.filename)throw TypeError(`SQLiteHistoryDatabaseAdapter requires a filename`);let t=e.busyTimeoutMs??5e3;this._database=new c.default(e.filename,{timeout:t});try{this._database.exec(`PRAGMA busy_timeout = ${t};`),this._initializeSchema()}catch(e){throw this._database.close(),e}}async getLatestRecord(e,t){this._assertOpen();let n=this._latest(t);return n?g(n):null}async appendRecord(e,t,n){return this._assertOpen(),m(t),this._transaction(()=>{let e=this._database.prepare(`SELECT * FROM collaboration_history_records WHERE unit_id = ? AND start_revision = ?`).get(t.unitID,t.startRevision);if(e)return{status:e.user_id===t.userID&&e.created_at_ms===t.createdAt&&e.origin===t.origin&&e.additional_fields===(t.additionalFields??null)?`already-exists`:`conflict`};let r=this._latest(t.unitID)?.start_revision??null;return r!==n.expectedLatestStartRevision||t.startRevision<=(r??0)?{status:`conflict`}:(this._database.prepare(`INSERT INTO collaboration_history_records
21
+ `,m=class{_database;_disposed=!1;constructor(e){if(!e.filename)throw TypeError(`SQLiteHistoryDatabaseAdapter requires a filename`);let t=e.busyTimeoutMs??5e3;this._database=new c.default(e.filename,{timeout:t});try{this._database.exec(`PRAGMA busy_timeout = ${t};`),this._initializeSchema()}catch(e){throw this._database.close(),e}}async getLatestRecord(e,t){this._assertOpen();let n=this._latest(t);return n?_(n):null}async appendRecord(e,t,n){return this._assertOpen(),h(t),this._transaction(()=>{let e=this._database.prepare(`SELECT * FROM collaboration_history_records WHERE unit_id = ? AND start_revision = ?`).get(t.unitID,t.startRevision);if(e)return{status:e.user_id===t.userID&&e.created_at_ms===t.createdAt&&e.origin===t.origin&&e.additional_fields===(t.additionalFields??null)?`already-exists`:`conflict`};let r=this._latest(t.unitID)?.start_revision??null;return r!==n.expectedLatestStartRevision||t.startRevision<=(r??0)?{status:`conflict`}:(this._database.prepare(`INSERT INTO collaboration_history_records
17
22
  (unit_id, start_revision, user_id, created_at_ms, origin, additional_fields)
18
23
  VALUES (?, ?, ?, ?, ?, ?)`).run(t.unitID,t.startRevision,t.userID,t.createdAt,t.origin,t.additionalFields??null),{status:`appended`})})}async listRecords(e,t,n){this._assertOpen();let r=[n.throughRevision,n.throughRevision,t,n.throughRevision],i=[];n.beforeRevision!==void 0&&(i.push(`r.start_revision < ?`),r.push(n.beforeRevision)),n.origin&&(i.push(`r.origin = ?`),r.push(n.origin)),n.userIDs?.length&&(i.push(`r.user_id IN (${n.userIDs.map(()=>`?`).join(`, `)})`),r.push(...n.userIDs)),r.push(n.length+1);let a=this._database.prepare(`
19
24
  SELECT r.*, MIN(?, COALESCE((
@@ -25,28 +30,23 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
25
30
  WHERE r.unit_id = ? AND r.start_revision <= ?
26
31
  ${i.length?`AND ${i.join(` AND `)}`:``}
27
32
  ORDER BY r.start_revision DESC LIMIT ?
28
- `).all(...r);return{records:a.slice(0,n.length).map(e=>({record:g(e),endRevision:e.end_revision})),hasMore:a.length>n.length}}async listCreators(e,t,n){this._assertOpen();let r=this._database.prepare(`SELECT DISTINCT user_id, origin FROM collaboration_history_records
29
- WHERE unit_id = ? AND start_revision <= ? ORDER BY user_id, origin`).all(t,n.throughRevision),i=new Map;for(let e of r){let t=i.get(e.user_id)??[];t.push(e.origin),i.set(e.user_id,t)}return[...i].map(([e,t])=>({userID:e,origins:t}))}async dispose(){this._disposed||(this._disposed=!0,this._database.close())}_latest(e){return this._database.prepare(`SELECT * FROM collaboration_history_records WHERE unit_id = ? ORDER BY start_revision DESC LIMIT 1`).get(e)}_initializeSchema(){this._transaction(()=>{this._database.exec(`
30
- CREATE TABLE IF NOT EXISTS collaboration_schema_versions (
31
- component TEXT PRIMARY KEY,
32
- version INTEGER NOT NULL CHECK (version >= 1)
33
- );
34
- `);let e=this._readSchemaVersion();if(e!==2){if(e!==void 0)throw h(e);this._database.exec(`
35
- ${d}
33
+ `).all(...r);return{records:a.slice(0,n.length).map(e=>({record:_(e),endRevision:e.end_revision})),hasMore:a.length>n.length}}async listCreators(e,t,n){this._assertOpen();let r=this._database.prepare(`SELECT DISTINCT user_id, origin FROM collaboration_history_records
34
+ WHERE unit_id = ? AND start_revision <= ? ORDER BY user_id, origin`).all(t,n.throughRevision),i=new Map;for(let e of r){let t=i.get(e.user_id)??[];t.push(e.origin),i.set(e.user_id,t)}return[...i].map(([e,t])=>({userID:e,origins:t}))}async dispose(){this._disposed||(this._disposed=!0,this._database.close())}_latest(e){return this._database.prepare(`SELECT * FROM collaboration_history_records WHERE unit_id = ? ORDER BY start_revision DESC LIMIT 1`).get(e)}_initializeSchema(){this._transaction(()=>{this._database.exec(d);let e=this._readSchemaVersion();if(e!==2){if(e!==void 0)throw g(e);this._database.exec(`
36
35
  ${f}
36
+ ${p}
37
37
  INSERT INTO collaboration_schema_versions (component, version)
38
38
  VALUES ('${u}', 2);
39
- `)}})}_readSchemaVersion(){return this._database.prepare(`SELECT version FROM collaboration_schema_versions WHERE component = ?`).get(u)?.version}_transaction(e){this._database.exec(`BEGIN IMMEDIATE;`);try{let t=e();return this._database.exec(`COMMIT;`),t}catch(e){try{this._database.exec(`ROLLBACK;`)}catch{}throw e}}_assertOpen(){if(this._disposed)throw Error(`SQLite History Database Adapter is disposed`)}};function m(e){if(!e.unitID||!e.userID||!Number.isSafeInteger(e.startRevision)||e.startRevision<1||!Number.isSafeInteger(e.createdAt)||e.createdAt<0)throw TypeError(`History record is invalid`)}function h(e){return Error(`History schema version ${e} is not supported by this adapter (expected 2); ${e<2?`run migrateSQLiteHistory first`:`upgrade the adapter`}`)}function g(e){return{unitID:e.unit_id,startRevision:e.start_revision,userID:e.user_id,createdAt:e.created_at_ms,origin:e.origin,...e.additional_fields===null?{}:{additionalFields:e.additional_fields}}}function _(e,t){let n=new c.default(e,{fileMustExist:!0}),r=!1;try{n.exec(`BEGIN IMMEDIATE;`),r=!0,t(n),n.exec(`COMMIT;`),r=!1}finally{try{r&&n.exec(`ROLLBACK;`)}finally{n.close()}}}function v(e,t){return e.prepare(`SELECT version FROM collaboration_schema_versions WHERE component = ?`).get(t)?.version}async function y(e){_(e.filename,e=>{if(v(e,`history`)!==1)throw Error(`migrateSQLiteHistoryV1ToV2 requires history schema version 1`);if(v(e,`core`)===1)throw Error(`Migrate SQLite Core v1 before History so creation facts remain available`);let t=v(e,`worktree`);if(t!==void 0&&t<3)throw Error(`Migrate SQLite Worktree before History so creation facts remain available`);if(e.prepare(`SELECT 1 FROM collaboration_history_revisions AS r
39
+ `)}})}_readSchemaVersion(){return this._database.prepare(`SELECT version FROM collaboration_schema_versions WHERE component = ?`).get(u)?.version}_transaction(e){this._database.exec(`BEGIN IMMEDIATE;`);try{let t=e();return this._database.exec(`COMMIT;`),t}catch(e){try{this._database.exec(`ROLLBACK;`)}catch{}throw e}}_assertOpen(){if(this._disposed)throw Error(`SQLite History Database Adapter is disposed`)}};function h(e){if(!e.unitID||!e.userID||!Number.isSafeInteger(e.startRevision)||e.startRevision<1||!Number.isSafeInteger(e.createdAt)||e.createdAt<0)throw TypeError(`History record is invalid`)}function g(e){return Error(`History schema version ${e} is not supported by this adapter (expected 2); ${e<2?`run migrateSQLiteHistory first`:`upgrade the adapter`}`)}function _(e){return{unitID:e.unit_id,startRevision:e.start_revision,userID:e.user_id,createdAt:e.created_at_ms,origin:e.origin,...e.additional_fields===null?{}:{additionalFields:e.additional_fields}}}function v(e,t){let n=new c.default(e,{fileMustExist:!0}),r=!1;try{n.exec(`BEGIN IMMEDIATE;`),r=!0,t(n),n.exec(`COMMIT;`),r=!1}finally{try{r&&n.exec(`ROLLBACK;`)}finally{n.close()}}}function y(e,t){return e.prepare(`SELECT version FROM collaboration_schema_versions WHERE component = ?`).get(t)?.version}async function b(e){v(e.filename,e=>{if(y(e,`history`)!==1)throw Error(`migrateSQLiteHistoryV1ToV2 requires history schema version 1`);if(y(e,`core`)===1)throw Error(`Migrate SQLite Core v1 before History so creation facts remain available`);let t=y(e,`worktree`);if(t!==void 0&&t<3)throw Error(`Migrate SQLite Worktree before History so creation facts remain available`);if(e.prepare(`SELECT 1 FROM collaboration_history_revisions AS r
40
40
  LEFT JOIN collaboration_history_revisions AS first
41
41
  ON first.unit_id = r.unit_id AND first.revision = r.history_revision
42
42
  WHERE r.history_revision > r.revision OR first.revision IS NULL
43
43
  OR first.history_revision != first.revision OR first.user_id = ''
44
44
  OR typeof(first.committed_at) != 'integer'
45
45
  OR first.committed_at < 0 OR first.committed_at > 9007199254740991
46
- LIMIT 1`).get())throw Error(`History v1 contains a missing or invalid segment starting revision`);e.exec(d),e.exec(`
46
+ LIMIT 1`).get())throw Error(`History v1 contains a missing or invalid segment starting revision`);e.exec(f),e.exec(`
47
47
  INSERT INTO collaboration_history_records
48
48
  (unit_id, start_revision, user_id, created_at_ms, origin, additional_fields)
49
49
  SELECT unit_id, revision, user_id, committed_at, origin, additional_fields
50
50
  FROM collaboration_history_revisions WHERE revision = history_revision;
51
51
  DROP TABLE collaboration_history_revisions;
52
- `),e.exec(f),e.prepare(`UPDATE collaboration_schema_versions SET version = 2 WHERE component = ?`).run(u)})}var b=[y];async function x(e){let t=S(e.filename);if(t===2)return{from:t,to:t};if(t>2)throw Error(`History schema version ${t} is newer than this package supports (2)`);let n=e.backupFilename??`${e.filename}.history-v${t}.backup`;C(e.filename,n);for(let n of b.slice(t-1))await n(e);return{from:t,to:2,backupFilename:n}}function S(e){let t=new c.default(e,{fileMustExist:!0});try{let e=v(t,u);if(e===void 0||!Number.isInteger(e)||e<1)throw Error(`The database has no history schema version to migrate from`);return e}catch(e){throw e instanceof Error&&e.message.startsWith(`The database has no history`)?e:Error(`The database has no history schema version to migrate from`)}finally{t.close()}}function C(e,t){if((0,l.existsSync)(t))throw Error(`Backup target already exists: ${t}`);let n=new c.default(e,{fileMustExist:!0});try{n.prepare(`VACUUM INTO ?`).run(t)}finally{n.close()}}exports.SQLiteHistoryDatabaseAdapter=p,exports.migrateSQLiteHistory=x,exports.migrateSQLiteHistoryV1ToV2=y;
52
+ `),e.exec(p),e.prepare(`UPDATE collaboration_schema_versions SET version = 2 WHERE component = ?`).run(u)})}var x=[b];async function S(e){let t=C(e.filename);if(t===2)return{from:t,to:t};if(t>2)throw Error(`History schema version ${t} is newer than this package supports (2)`);let n=e.backupFilename??`${e.filename}.history-v${t}.backup`;w(e.filename,n);for(let n of x.slice(t-1))await n(e);return{from:t,to:2,backupFilename:n}}function C(e){let t=new c.default(e,{fileMustExist:!0});try{let e=y(t,u);if(e===void 0||!Number.isInteger(e)||e<1)throw Error(`The database has no history schema version to migrate from`);return e}catch(e){throw e instanceof Error&&e.message.startsWith(`The database has no history`)?e:Error(`The database has no history schema version to migrate from`)}finally{t.close()}}function w(e,t){if((0,l.existsSync)(t))throw Error(`Backup target already exists: ${t}`);let n=new c.default(e,{fileMustExist:!0});try{n.prepare(`VACUUM INTO ?`).run(t)}finally{n.close()}}exports.SQLiteHistoryDatabaseAdapter=m,exports.migrateSQLiteHistory=S,exports.migrateSQLiteHistoryV1ToV2=b;
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { AppendHistoryRecordResult, HistoryCreatorIndex, HistoryDatabaseContext, HistoryRecord, IHistoryDatabaseAdapter, ListHistoryRecordsOptions, ListHistoryRecordsResult } from "@univerjs-pro/collaboration-history-service";
2
2
 
3
- //#region src/sqlite-history-database-adapter.d.ts
3
+ // src/sqlite-history-database-adapter.d.ts
4
4
  interface SQLiteHistoryDatabaseAdapterOptions {
5
5
  /** SQLite filename or `:memory:`. The parent directory must already exist. */
6
6
  readonly filename: string;
@@ -35,8 +35,6 @@ declare class SQLiteHistoryDatabaseAdapter implements IHistoryDatabaseAdapter {
35
35
  private _transaction;
36
36
  private _assertOpen;
37
37
  }
38
- //#endregion
39
- //#region src/migrations/migrate.d.ts
40
38
  interface SQLiteHistoryMigrationOptions {
41
39
  readonly filename: string;
42
40
  /** Where the backup is written before any change. Defaults to `<filename>.history-v<from>.backup`. */
@@ -56,8 +54,6 @@ interface SQLiteHistoryMigrationResult {
56
54
  * before this one. Stop writers before calling.
57
55
  */
58
56
  declare function migrateSQLiteHistory(options: SQLiteHistoryMigrationOptions): Promise<SQLiteHistoryMigrationResult>;
59
- //#endregion
60
- //#region src/migrations/v1-to-v2.d.ts
61
57
  interface SQLiteHistoryV1ToV2MigrationOptions {
62
58
  readonly filename: string;
63
59
  }
@@ -67,5 +63,4 @@ interface SQLiteHistoryV1ToV2MigrationOptions {
67
63
  * same file first: their migrations read creation facts from the v1 history rows.
68
64
  */
69
65
  declare function migrateSQLiteHistoryV1ToV2(options: SQLiteHistoryV1ToV2MigrationOptions): Promise<void>;
70
- //#endregion
71
66
  export { SQLiteHistoryDatabaseAdapter, type SQLiteHistoryDatabaseAdapterOptions, type SQLiteHistoryMigrationOptions, type SQLiteHistoryMigrationResult, type SQLiteHistoryV1ToV2MigrationOptions, migrateSQLiteHistory, migrateSQLiteHistoryV1ToV2 };
package/package.json CHANGED
@@ -11,7 +11,7 @@
11
11
  "engines": {
12
12
  "node": ">=22"
13
13
  },
14
- "version": "1.4.0",
14
+ "version": "1.6.0",
15
15
  "main": "./dist/index.cjs",
16
16
  "module": "./dist/index.mjs",
17
17
  "types": "./dist/index.d.ts",
@@ -29,6 +29,6 @@
29
29
  "libsql": "^0.5.29"
30
30
  },
31
31
  "peerDependencies": {
32
- "@univerjs-pro/collaboration-history-service": "1.4.0"
32
+ "@univerjs-pro/collaboration-history-service": "1.6.0"
33
33
  }
34
34
  }