From b0f6dfb89144c6e25bbedfb17777ebb5b0c85497 Mon Sep 17 00:00:00 2001 From: streamich Date: Tue, 2 Jun 2026 20:09:01 +0200 Subject: [PATCH 01/14] =?UTF-8?q?chore:=20=F0=9F=A4=96=20make=20crdt=20ser?= =?UTF-8?q?ver=20publishable?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/json-crdt-server/bin/json-crdt-server.js | 3 +++ packages/json-crdt-server/package.json | 1 - 2 files changed, 3 insertions(+), 1 deletion(-) create mode 100755 packages/json-crdt-server/bin/json-crdt-server.js diff --git a/packages/json-crdt-server/bin/json-crdt-server.js b/packages/json-crdt-server/bin/json-crdt-server.js new file mode 100755 index 0000000000..fd7bdad868 --- /dev/null +++ b/packages/json-crdt-server/bin/json-crdt-server.js @@ -0,0 +1,3 @@ +#!/usr/bin/env node + +require('../lib/main'); diff --git a/packages/json-crdt-server/package.json b/packages/json-crdt-server/package.json index 1260fde909..07c1a2a266 100644 --- a/packages/json-crdt-server/package.json +++ b/packages/json-crdt-server/package.json @@ -70,7 +70,6 @@ "engines": { "node": ">=18.0" }, - "private": true, "scripts": { "start": "npx ts-node --transpile-only src/main.ts", "clean": "npx rimraf lib", From 9ec7c0fde672a7664588d25003f9391ff71a5535 Mon Sep 17 00:00:00 2001 From: streamich Date: Tue, 2 Jun 2026 22:41:14 +0200 Subject: [PATCH 02/14] =?UTF-8?q?chore:=20=F0=9F=A4=96=20cleanup=20collabo?= =?UTF-8?q?rative-input=20components?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ClickableJsonCrdt/nodes/JsonCrdtStrNode/StrEdit.tsx | 4 ++-- packages/collaborative-input/docs/text.md | 9 ++------- .../src/editor/components/CollaborativeInput.tsx | 2 +- 3 files changed, 5 insertions(+), 10 deletions(-) diff --git a/packages/click-json/src/ClickableJsonCrdt/nodes/JsonCrdtStrNode/StrEdit.tsx b/packages/click-json/src/ClickableJsonCrdt/nodes/JsonCrdtStrNode/StrEdit.tsx index e6e8b271c5..ee9dc5876f 100644 --- a/packages/click-json/src/ClickableJsonCrdt/nodes/JsonCrdtStrNode/StrEdit.tsx +++ b/packages/click-json/src/ClickableJsonCrdt/nodes/JsonCrdtStrNode/StrEdit.tsx @@ -1,15 +1,15 @@ import * as React from 'react'; import {theme} from 'nano-theme'; -import {bind} from 'collaborative-input'; +import {bind} from '@jsonjoy.com/collaborative-input'; import {FlexibleInput} from 'flexible-input'; import {useT} from 'use-t'; -import type {NodeRef} from '../../NodeRef'; import * as css from '../../../css'; import {selectOnFocus} from '../../../utils/selectOnFocus'; import {inputStyle} from '../../../ClickableJson/utils'; import {CancelAction} from '../../../buttons/Action/CancelAction'; import {SubmitAction} from '../../../buttons/Action/SubmitAction'; import {useJsonCrdt} from '../../context'; +import type {NodeRef} from '../../NodeRef'; import type {StrNode} from 'json-joy/lib/json-crdt'; export interface StrEditProps { diff --git a/packages/collaborative-input/docs/text.md b/packages/collaborative-input/docs/text.md index 242c52119a..06993f39ce 100644 --- a/packages/collaborative-input/docs/text.md +++ b/packages/collaborative-input/docs/text.md @@ -10,13 +10,13 @@ JSON CRDT data structures. It allows multiple users to edit the `` and Installation: ``` -npm install json-joy collaborative-input +npm install json-joy @jsonjoy.com/collaborative-input ``` Usage: ```ts -import {bind} from 'collaborative-input'; +import {bind} from '@jsonjoy.com/collaborative-input'; const str = model.api.str(['path', 'to', 'string']); const input = document.getElementById('input'); @@ -25,8 +25,3 @@ const unbind = bind(str, input); // When done, unbind the binding. unbind(); ``` - - -## Preview - -See [demo](https://streamich.github.io/collaborative-input). diff --git a/packages/peritext/src/editor/components/CollaborativeInput.tsx b/packages/peritext/src/editor/components/CollaborativeInput.tsx index 4f24976fff..618541bb45 100644 --- a/packages/peritext/src/editor/components/CollaborativeInput.tsx +++ b/packages/peritext/src/editor/components/CollaborativeInput.tsx @@ -1,5 +1,5 @@ import {createElement, useMemo, useLayoutEffect} from 'react'; -import {bind} from 'collaborative-input'; +import {bind} from '@jsonjoy.com/collaborative-input'; import type {CollaborativeStr} from 'collaborative-editor'; import type {UiLifeCycles} from '@jsonjoy.com/ui/lib/types'; From 3cf5dd63b731faa1732181c8a1b345462f7dce0f Mon Sep 17 00:00:00 2001 From: streamich Date: Mon, 6 Jul 2026 15:18:46 +0200 Subject: [PATCH 03/14] =?UTF-8?q?feat:=20=F0=9F=8E=B8=20create=20json-hash?= =?UTF-8?q?=20package?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/json-hash/LICENSE | 201 ++++++++++++++++++ packages/json-hash/README.md | 22 ++ packages/json-hash/SECURITY.md | 13 ++ packages/json-hash/package.json | 79 +++++++ packages/json-hash/src/__tests__/hash.spec.ts | 76 +++++++ packages/json-hash/src/hash.ts | 70 ++++++ packages/json-hash/src/index.ts | 1 + packages/json-hash/tsconfig.build.json | 33 +++ packages/json-hash/tsconfig.json | 34 +++ tsconfig.solution.json | 1 + yarn.lock | 13 ++ 11 files changed, 543 insertions(+) create mode 100644 packages/json-hash/LICENSE create mode 100644 packages/json-hash/README.md create mode 100644 packages/json-hash/SECURITY.md create mode 100644 packages/json-hash/package.json create mode 100644 packages/json-hash/src/__tests__/hash.spec.ts create mode 100644 packages/json-hash/src/hash.ts create mode 100644 packages/json-hash/src/index.ts create mode 100644 packages/json-hash/tsconfig.build.json create mode 100644 packages/json-hash/tsconfig.json diff --git a/packages/json-hash/LICENSE b/packages/json-hash/LICENSE new file mode 100644 index 0000000000..75635b39a3 --- /dev/null +++ b/packages/json-hash/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2023 Vadims @streamich Daleckis + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/packages/json-hash/README.md b/packages/json-hash/README.md new file mode 100644 index 0000000000..4314e1bd9e --- /dev/null +++ b/packages/json-hash/README.md @@ -0,0 +1,22 @@ +# `@jsonjoy.com/json-hash` + +Computes a 32-bit hash given an arbitrary JSON value. Sorts keys, so objects +with different key orders will have the same hash. + +Implements DJB2 hash function. + +```ts +import {hash} from '@jsonjoy.com/json-hash'; + +const num1 = hash({ + foo: 1, + bar: 2, +}); + +const num2 = hash({ + bar: 2, + foo: 1, +}); + +num1 === num2; // true +``` diff --git a/packages/json-hash/SECURITY.md b/packages/json-hash/SECURITY.md new file mode 100644 index 0000000000..a5497b62af --- /dev/null +++ b/packages/json-hash/SECURITY.md @@ -0,0 +1,13 @@ +# Security Policy + +## Supported Versions + +We release patches for security vulnerabilities. The latest major version +will support security patches. + +## Reporting a Vulnerability + +Please report (suspected) security vulnerabilities to +**[streamich@gmail.com](mailto:streamich@gmail.com)**. We will try to respond +within 48 hours. If the issue is confirmed, we will release a patch as soon +as possible depending on complexity. diff --git a/packages/json-hash/package.json b/packages/json-hash/package.json new file mode 100644 index 0000000000..61ab32bd83 --- /dev/null +++ b/packages/json-hash/package.json @@ -0,0 +1,79 @@ +{ + "name": "@jsonjoy.com/json-hash", + "publishConfig": { + "access": "public" + }, + "version": "18.28.0", + "description": "Structural hashing for JSON values", + "author": { + "name": "streamich", + "url": "https://github.com/streamich" + }, + "homepage": "https://github.com/streamich/json-joy/tree/master/packages/json-hash", + "repository": { + "type": "git", + "url": "https://github.com/streamich/json-joy.git", + "directory": "packages/json-hash" + }, + "license": "Apache-2.0", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/streamich" + }, + "keywords": [ + "json", + "hash", + "json-hash", + "structural-hash", + "djb2", + "checksum", + "digest" + ], + "peerDependencies": { + "tslib": "*" + }, + "dependencies": { + "@jsonjoy.com/json-pack": "workspace:*", + "@jsonjoy.com/util": "workspace:*" + }, + "devDependencies": { + "@jsonjoy.com/json-random": "workspace:*" + }, + "engines": { + "node": ">=10.0" + }, + "main": "lib/index.js", + "types": "lib/index.d.ts", + "typings": "lib/index.d.ts", + "files": [ + "LICENSE", + "lib/" + ], + "scripts": { + "clean": "npx rimraf lib typedocs coverage gh-pages yarn-error.log", + "build": "tsc -b tsconfig.build.json", + "typedoc": "typedoc", + "typecheck": "tsc -b --noEmit" + }, + "jest": { + "preset": "ts-jest", + "testEnvironment": "node", + "moduleFileExtensions": [ + "ts", + "js", + "tsx" + ], + "transform": { + "^.+\\.tsx?$": "ts-jest" + }, + "transformIgnorePatterns": [ + ".*/node_modules/.*" + ], + "testRegex": ".*/(__tests__|__jest__|demo)/.*(? { + const res1 = hash({}); + const res2 = hash({}); + expect(res1).toBe(res2); +}); + +test('returns the same hash for empty arrays', () => { + const res1 = hash([]); + const res2 = hash([]); + const res3 = hash({}); + expect(res1).toBe(res2); + expect(res1).not.toBe(res3); +}); + +test('returns the same hash for empty strings', () => { + const res1 = hash(''); + const res2 = hash(''); + const res3 = hash({}); + const res4 = hash([]); + expect(res1).toBe(res2); + expect(res1).not.toBe(res3); + expect(res1).not.toBe(res4); +}); + +test('returns the same hash for object with keys', () => { + const res1 = hash({foo: 123, bar: 'asdf'}); + const res2 = hash({foo: 123, bar: 'asdf'}); + expect(res1).toBe(res2); +}); + +test('returns the same hash regardless of key order', () => { + const res1 = hash({bar: 'asdf', foo: 123}); + const res2 = hash({foo: 123, bar: 'asdf'}); + expect(res1).toBe(res2); +}); + +test('returns the same hash for array with values', () => { + const res1 = hash([true, 'asdf', false]); + const res2 = hash([true, 'asdf', false]); + expect(res1).toBe(res2); +}); + +test('different key order returns the same hash', () => { + const res1 = hash({bar: 'asdf', foo: 123}); + const res2 = hash({foo: 123, bar: 'asdf'}); + expect(res1).toBe(res2); +}); + +test('same hash for binary data', () => { + const res1 = hash({data: new Uint8Array([1, 2, 3])}); + const res2 = hash({data: new Uint8Array([1, 2, 3])}); + expect(res1).toBe(res2); +}); + +test('different hash for binary data', () => { + const res1 = hash({data: new Uint8Array([1, 2, 3])}); + const res2 = hash({data: new Uint8Array([1, 2, 4])}); + expect(res1).not.toBe(res2); +}); + +test('returns different hash for random JSON values', () => { + for (let i = 0; i < 100; i++) { + const res1 = hash(RandomJson.generate() as any); + const res2 = hash(RandomJson.generate() as any); + expect(res1).not.toBe(res2); + } +}); + +test('returns different hash for first 100K numbers', () => { + const set = new Set(); + for (let i = 0; i < 100000; i++) set.add(hash(i)); + expect(set.size).toBe(100000); +}); diff --git a/packages/json-hash/src/hash.ts b/packages/json-hash/src/hash.ts new file mode 100644 index 0000000000..c3a778e55c --- /dev/null +++ b/packages/json-hash/src/hash.ts @@ -0,0 +1,70 @@ +import {sort} from '@jsonjoy.com/util/lib/sort/insertion'; +import type {PackValue} from '@jsonjoy.com/json-pack/lib/types'; + +export enum CONST { + START_STATE = 5381, + + NULL = 982452847, + TRUE = 982453247, + FALSE = 982454243, + ARRAY = 982452259, + STRING = 982453601, + OBJECT = 982454533, + BINARY = 982454837, +} + +export const updateNum = (state: number, num: number): number => { + return (state << 5) + state + num; +}; + +export const updateStr = (state: number, str: string): number => { + const length = str.length; + state = updateNum(state, CONST.STRING); + state = updateNum(state, length); + let i = length; + while (i) state = (state << 5) + state + str.charCodeAt(--i); + return state; +}; + +export const updateBin = (state: number, bin: Uint8Array): number => { + const length = bin.length; + state = updateNum(state, CONST.BINARY); + state = updateNum(state, length); + let i = length; + while (i) state = (state << 5) + state + bin[--i]; + return state; +}; + +export const updateJson = (state: number, json: unknown): number => { + switch (typeof json) { + case 'number': + return updateNum(state, json); + case 'string': + state = updateNum(state, CONST.STRING); + return updateStr(state, json); + case 'object': { + if (json === null) return updateNum(state, CONST.NULL); + if (Array.isArray(json)) { + const length = json.length; + state = updateNum(state, CONST.ARRAY); + for (let i = 0; i < length; i++) state = updateJson(state, json[i]); + return state; + } + if (json instanceof Uint8Array) return updateBin(state, json); + state = updateNum(state, CONST.OBJECT); + const keys = sort(Object.keys(json as object)); + const length = keys.length; + for (let i = 0; i < length; i++) { + const key = keys[i]; + state = updateStr(state, key); + state = updateJson(state, (json as any)[key]); + } + return state; + } + case 'boolean': + return updateNum(state, json ? CONST.TRUE : CONST.FALSE); + } + return state; +}; + +export const hash = (json: PackValue) => updateJson(CONST.START_STATE, json) >>> 0; diff --git a/packages/json-hash/src/index.ts b/packages/json-hash/src/index.ts new file mode 100644 index 0000000000..6719163c39 --- /dev/null +++ b/packages/json-hash/src/index.ts @@ -0,0 +1 @@ +export * from './hash'; diff --git a/packages/json-hash/tsconfig.build.json b/packages/json-hash/tsconfig.build.json new file mode 100644 index 0000000000..71542832c5 --- /dev/null +++ b/packages/json-hash/tsconfig.build.json @@ -0,0 +1,33 @@ +{ + "extends": "./tsconfig", + "compilerOptions": { + "sourceMap": false, + "rootDir": "./src", + "tsBuildInfoFile": "./lib/.tsbuildinfo" + }, + "exclude": [ + "src/demo", + "src/__tests__", + "src/**/__demos__/**/*.*", + "src/**/__tests__/**/*.*", + "src/**/__bench__/**/*.*", + "src/**/__mocks__/**/*.*", + "src/**/__jest__/**/*.*", + "src/**/__mocha__/**/*.*", + "src/**/__tap__/**/*.*", + "src/**/__tape__/**/*.*", + "*.test.ts", + "*.spec.ts", + "src/**/__stories__/**/*.*", + "src/**/*.stories.ts", + "src/**/*.stories.tsx" + ], + "references": [ + { + "path": "../json-pack/tsconfig.build.json" + }, + { + "path": "../util/tsconfig.build.json" + } + ] +} diff --git a/packages/json-hash/tsconfig.json b/packages/json-hash/tsconfig.json new file mode 100644 index 0000000000..58aa5814c5 --- /dev/null +++ b/packages/json-hash/tsconfig.json @@ -0,0 +1,34 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "rootDir": "./src", + "outDir": "./lib" + }, + "include": [ + "src" + ], + "exclude": [ + "src/demo", + "src/__tests__", + "src/**/__demos__/**/*.*", + "src/**/__tests__/**/*.*", + "src/**/__bench__/**/*.*", + "src/**/__mocks__/**/*.*", + "src/**/__jest__/**/*.*", + "src/**/__mocha__/**/*.*", + "src/**/__tap__/**/*.*", + "src/**/__tape__/**/*.*", + "*.test.ts", + "*.spec.ts", + "src/**/*.stories.ts", + "src/**/*.stories.tsx" + ], + "references": [ + { + "path": "../json-pack" + }, + { + "path": "../util" + } + ] +} diff --git a/tsconfig.solution.json b/tsconfig.solution.json index d1666815e6..a7ac56ec98 100644 --- a/tsconfig.solution.json +++ b/tsconfig.solution.json @@ -6,6 +6,7 @@ { "path": "packages/codegen/tsconfig.build.json" }, { "path": "packages/channel/tsconfig.build.json" }, { "path": "packages/json-equal/tsconfig.build.json" }, + { "path": "packages/json-hash/tsconfig.build.json" }, { "path": "packages/json-random/tsconfig.build.json" }, { "path": "packages/json-path/tsconfig.build.json" }, { "path": "packages/keyboard/tsconfig.build.json" }, diff --git a/yarn.lock b/yarn.lock index c82f01abf1..97ab7ea444 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2456,6 +2456,18 @@ __metadata: languageName: unknown linkType: soft +"@jsonjoy.com/json-hash@workspace:*, @jsonjoy.com/json-hash@workspace:packages/json-hash": + version: 0.0.0-use.local + resolution: "@jsonjoy.com/json-hash@workspace:packages/json-hash" + dependencies: + "@jsonjoy.com/json-pack": "workspace:*" + "@jsonjoy.com/json-random": "workspace:*" + "@jsonjoy.com/util": "workspace:*" + peerDependencies: + tslib: "*" + languageName: unknown + linkType: soft + "@jsonjoy.com/json-pack@npm:17.67.0, @jsonjoy.com/json-pack@npm:^17.65.0": version: 17.67.0 resolution: "@jsonjoy.com/json-pack@npm:17.67.0" @@ -10095,6 +10107,7 @@ __metadata: "@jsonjoy.com/buffers": "workspace:*" "@jsonjoy.com/json-equal": "workspace:*" "@jsonjoy.com/json-expression": "workspace:*" + "@jsonjoy.com/json-hash": "workspace:*" "@jsonjoy.com/json-pack": "workspace:*" "@jsonjoy.com/json-pointer": "workspace:*" "@jsonjoy.com/json-random": "workspace:*" From 502e246b99afdeff22b711b26223ff01e1aa7d50 Mon Sep 17 00:00:00 2001 From: streamich Date: Mon, 6 Jul 2026 15:21:22 +0200 Subject: [PATCH 04/14] =?UTF-8?q?feat:=20=F0=9F=8E=B8=20use=20the=20new=20?= =?UTF-8?q?json-hash=20package?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/json-joy/package.json | 1 + .../json-crdt-extensions/peritext/Peritext.ts | 2 +- .../peritext/block/Block.ts | 2 +- .../peritext/block/Inline.ts | 2 +- .../block/__tests__/Inline.key.spec.ts | 2 +- .../peritext/overlay/Overlay.ts | 2 +- .../peritext/rga/Range.ts | 2 +- .../peritext/slice/Slice.ts | 2 +- .../peritext/slice/Slices.ts | 2 +- .../peritext/util/ChunkSlice.ts | 2 +- packages/json-joy/src/json-crdt/hash.ts | 2 +- packages/json-joy/src/json-hash/README.md | 22 ------ .../src/json-hash/__tests__/hash.spec.ts | 76 ------------------- packages/json-joy/src/json-hash/hash.ts | 71 +---------------- packages/json-joy/src/json-hash/structHash.ts | 2 +- .../json-joy/src/json-hash/structHashCrdt.ts | 2 +- .../src/json-hash/structHashSchema.ts | 2 +- packages/json-joy/tsconfig.build.json | 3 + packages/json-joy/tsconfig.json | 3 + 19 files changed, 21 insertions(+), 181 deletions(-) delete mode 100644 packages/json-joy/src/json-hash/README.md delete mode 100644 packages/json-joy/src/json-hash/__tests__/hash.spec.ts diff --git a/packages/json-joy/package.json b/packages/json-joy/package.json index 4903a9c4e1..35ee329e3a 100644 --- a/packages/json-joy/package.json +++ b/packages/json-joy/package.json @@ -79,6 +79,7 @@ "@jsonjoy.com/buffers": "workspace:*", "@jsonjoy.com/json-equal": "workspace:*", "@jsonjoy.com/json-expression": "workspace:*", + "@jsonjoy.com/json-hash": "workspace:*", "@jsonjoy.com/json-pack": "workspace:*", "@jsonjoy.com/json-pointer": "workspace:*", "@jsonjoy.com/json-type": "workspace:*", diff --git a/packages/json-joy/src/json-crdt-extensions/peritext/Peritext.ts b/packages/json-joy/src/json-crdt-extensions/peritext/Peritext.ts index 8bc70318dd..2c8ff931e3 100644 --- a/packages/json-joy/src/json-crdt-extensions/peritext/Peritext.ts +++ b/packages/json-joy/src/json-crdt-extensions/peritext/Peritext.ts @@ -9,7 +9,7 @@ import {LocalSlices} from './slice/LocalSlices'; import {Overlay} from './overlay/Overlay'; import {tick} from '../../json-crdt-patch/clock'; import {Model, type StrApi} from '../../json-crdt/model'; -import {CONST, updateNum} from '../../json-hash/hash'; +import {CONST, updateNum} from '@jsonjoy.com/json-hash'; import {SESSION} from '../../json-crdt-patch/constants'; import {s} from '../../json-crdt-patch'; import {ExtraSlices} from './slice/ExtraSlices'; diff --git a/packages/json-joy/src/json-crdt-extensions/peritext/block/Block.ts b/packages/json-joy/src/json-crdt-extensions/peritext/block/Block.ts index 8f3fed6dfe..5f5c27974b 100644 --- a/packages/json-joy/src/json-crdt-extensions/peritext/block/Block.ts +++ b/packages/json-joy/src/json-crdt-extensions/peritext/block/Block.ts @@ -1,5 +1,5 @@ import {printTree} from 'tree-dump/lib/printTree'; -import {CONST, updateJson, updateNum} from '../../../json-hash/hash'; +import {CONST, updateJson, updateNum} from '@jsonjoy.com/json-hash'; import {UndEndIterator, type UndEndNext} from '../../../util/iterator'; import {Inline} from './Inline'; import {formatStep, getTag} from '../slice/util'; diff --git a/packages/json-joy/src/json-crdt-extensions/peritext/block/Inline.ts b/packages/json-joy/src/json-crdt-extensions/peritext/block/Inline.ts index 2a3f4c31e6..e75efeb086 100644 --- a/packages/json-joy/src/json-crdt-extensions/peritext/block/Inline.ts +++ b/packages/json-joy/src/json-crdt-extensions/peritext/block/Inline.ts @@ -5,7 +5,7 @@ import {Range} from '../rga/Range'; import {ChunkSlice} from '../util/ChunkSlice'; import {Cursor} from '../editor/Cursor'; import {hashId} from '../../../json-crdt/hash'; -import {updateNum} from '../../../json-hash/hash'; +import {updateNum} from '@jsonjoy.com/json-hash'; import {formatStep} from '../slice/util'; import type {Point} from '../rga/Point'; import type {OverlayPoint} from '../overlay/OverlayPoint'; diff --git a/packages/json-joy/src/json-crdt-extensions/peritext/block/__tests__/Inline.key.spec.ts b/packages/json-joy/src/json-crdt-extensions/peritext/block/__tests__/Inline.key.spec.ts index 652c19b670..aff3a7b5ce 100644 --- a/packages/json-joy/src/json-crdt-extensions/peritext/block/__tests__/Inline.key.spec.ts +++ b/packages/json-joy/src/json-crdt-extensions/peritext/block/__tests__/Inline.key.spec.ts @@ -1,6 +1,6 @@ import {Timestamp} from '../../../../json-crdt-patch'; import {updateId} from '../../../../json-crdt/hash'; -import {updateNum} from '../../../../json-hash/hash'; +import {updateNum} from '@jsonjoy.com/json-hash'; import { type Kit, setupKit, diff --git a/packages/json-joy/src/json-crdt-extensions/peritext/overlay/Overlay.ts b/packages/json-joy/src/json-crdt-extensions/peritext/overlay/Overlay.ts index 01a2212c7e..e587f1d6df 100644 --- a/packages/json-joy/src/json-crdt-extensions/peritext/overlay/Overlay.ts +++ b/packages/json-joy/src/json-crdt-extensions/peritext/overlay/Overlay.ts @@ -6,7 +6,7 @@ import {splay} from 'sonic-forest/lib/splay/util'; import {Anchor} from '../rga/constants'; import {OverlayPoint} from './OverlayPoint'; import {compare, type ITimestampStruct} from '../../../json-crdt-patch/clock'; -import {CONST, updateNum} from '../../../json-hash/hash'; +import {CONST, updateNum} from '@jsonjoy.com/json-hash'; import {Slice} from '../slice/Slice'; import {UndEndIterator, type UndEndNext} from '../../../util/iterator'; import {SliceStacking} from '../slice/constants'; diff --git a/packages/json-joy/src/json-crdt-extensions/peritext/rga/Range.ts b/packages/json-joy/src/json-crdt-extensions/peritext/rga/Range.ts index 79ea764c9e..ad66895806 100644 --- a/packages/json-joy/src/json-crdt-extensions/peritext/rga/Range.ts +++ b/packages/json-joy/src/json-crdt-extensions/peritext/rga/Range.ts @@ -1,6 +1,6 @@ import {Point} from './Point'; import {Anchor} from './constants'; -import {updateNum} from '../../../json-hash/hash'; +import {updateNum} from '@jsonjoy.com/json-hash'; import type {ITimestampStruct} from '../../../json-crdt-patch/clock'; import type {Printable} from 'tree-dump/lib/types'; import type {AbstractRga, Chunk} from '../../../json-crdt/nodes/rga'; diff --git a/packages/json-joy/src/json-crdt-extensions/peritext/slice/Slice.ts b/packages/json-joy/src/json-crdt-extensions/peritext/slice/Slice.ts index 5c7c5cff23..d0e1eed8b8 100644 --- a/packages/json-joy/src/json-crdt-extensions/peritext/slice/Slice.ts +++ b/packages/json-joy/src/json-crdt-extensions/peritext/slice/Slice.ts @@ -11,7 +11,7 @@ import { SliceStackingName, SliceTypeCon, } from './constants'; -import {CONST} from '../../../json-hash/hash'; +import {CONST} from '@jsonjoy.com/json-hash'; import {Timestamp} from '../../../json-crdt-patch/clock'; import {prettyOneLine} from '../../../json-pretty'; import {formatType, validateType} from './util'; diff --git a/packages/json-joy/src/json-crdt-extensions/peritext/slice/Slices.ts b/packages/json-joy/src/json-crdt-extensions/peritext/slice/Slices.ts index c728df2f55..28251443b3 100644 --- a/packages/json-joy/src/json-crdt-extensions/peritext/slice/Slices.ts +++ b/packages/json-joy/src/json-crdt-extensions/peritext/slice/Slices.ts @@ -3,7 +3,7 @@ import {printTree} from 'tree-dump/lib/printTree'; import {Slice} from './Slice'; import {Timespan, compare, tss} from '../../../json-crdt-patch/clock'; import {updateRga} from '../../../json-crdt/hash'; -import {CONST, updateNum} from '../../../json-hash/hash'; +import {CONST, updateNum} from '@jsonjoy.com/json-hash'; import {SliceHeaderShift, SliceStacking, SliceTupleIndex} from './constants'; import {VecNode} from '../../../json-crdt/nodes'; import {Anchor} from '../rga/constants'; diff --git a/packages/json-joy/src/json-crdt-extensions/peritext/util/ChunkSlice.ts b/packages/json-joy/src/json-crdt-extensions/peritext/util/ChunkSlice.ts index 086834bd0b..31480673fb 100644 --- a/packages/json-joy/src/json-crdt-extensions/peritext/util/ChunkSlice.ts +++ b/packages/json-joy/src/json-crdt-extensions/peritext/util/ChunkSlice.ts @@ -1,4 +1,4 @@ -import {CONST, updateNum} from '../../../json-hash/hash'; +import {CONST, updateNum} from '@jsonjoy.com/json-hash'; import {updateId} from '../../../json-crdt/hash'; import {type ITimestampStruct, Timestamp, printTs} from '../../../json-crdt-patch/clock'; import type {IChunkSlice} from './types'; diff --git a/packages/json-joy/src/json-crdt/hash.ts b/packages/json-joy/src/json-crdt/hash.ts index fd1c382add..27650c048c 100644 --- a/packages/json-joy/src/json-crdt/hash.ts +++ b/packages/json-joy/src/json-crdt/hash.ts @@ -1,4 +1,4 @@ -import {CONST, updateNum} from '../json-hash/hash'; +import {CONST, updateNum} from '@jsonjoy.com/json-hash'; import {ConNode, ValNode, ObjNode, VecNode, ArrNode} from './nodes'; import {AbstractRga} from './nodes/rga'; import {last2} from 'sonic-forest/lib/util2'; diff --git a/packages/json-joy/src/json-hash/README.md b/packages/json-joy/src/json-hash/README.md deleted file mode 100644 index fe423a3792..0000000000 --- a/packages/json-joy/src/json-hash/README.md +++ /dev/null @@ -1,22 +0,0 @@ -# `json-hash` - -Computes a 32-bit hash given an arbitrary JSON value. Sorts keys, so objects -with different key orders will have the same hash. - -Implements DJB2 hash function. - -```ts -import {hash} from 'json-joy/lib/json-hash'; - -const num1 = hash({ - foo: 1, - bar: 2, -}); - -const num2 = hash({ - bar: 2, - foo: 1, -}); - -num1 === num2; // true -``` diff --git a/packages/json-joy/src/json-hash/__tests__/hash.spec.ts b/packages/json-joy/src/json-hash/__tests__/hash.spec.ts deleted file mode 100644 index 0fc52295b3..0000000000 --- a/packages/json-joy/src/json-hash/__tests__/hash.spec.ts +++ /dev/null @@ -1,76 +0,0 @@ -import {hash} from '../hash'; -import {RandomJson} from '@jsonjoy.com/json-random'; - -test('returns the same hash for empty objects', () => { - const res1 = hash({}); - const res2 = hash({}); - expect(res1).toBe(res2); -}); - -test('returns the same hash for empty arrays', () => { - const res1 = hash([]); - const res2 = hash([]); - const res3 = hash({}); - expect(res1).toBe(res2); - expect(res1).not.toBe(res3); -}); - -test('returns the same hash for empty strings', () => { - const res1 = hash(''); - const res2 = hash(''); - const res3 = hash({}); - const res4 = hash([]); - expect(res1).toBe(res2); - expect(res1).not.toBe(res3); - expect(res1).not.toBe(res4); -}); - -test('returns the same hash for object with keys', () => { - const res1 = hash({foo: 123, bar: 'asdf'}); - const res2 = hash({foo: 123, bar: 'asdf'}); - expect(res1).toBe(res2); -}); - -test('returns the same hash regardless of key order', () => { - const res1 = hash({bar: 'asdf', foo: 123}); - const res2 = hash({foo: 123, bar: 'asdf'}); - expect(res1).toBe(res2); -}); - -test('returns the same hash for array with values', () => { - const res1 = hash([true, 'asdf', false]); - const res2 = hash([true, 'asdf', false]); - expect(res1).toBe(res2); -}); - -test('different key order returns the same hash', () => { - const res1 = hash({bar: 'asdf', foo: 123}); - const res2 = hash({foo: 123, bar: 'asdf'}); - expect(res1).toBe(res2); -}); - -test('same hash for binary data', () => { - const res1 = hash({data: new Uint8Array([1, 2, 3])}); - const res2 = hash({data: new Uint8Array([1, 2, 3])}); - expect(res1).toBe(res2); -}); - -test('different hash for binary data', () => { - const res1 = hash({data: new Uint8Array([1, 2, 3])}); - const res2 = hash({data: new Uint8Array([1, 2, 4])}); - expect(res1).not.toBe(res2); -}); - -test('returns different hash for random JSON values', () => { - for (let i = 0; i < 100; i++) { - const res1 = hash(RandomJson.generate() as any); - const res2 = hash(RandomJson.generate() as any); - expect(res1).not.toBe(res2); - } -}); - -test('returns different hash for first 100K numbers', () => { - const set = new Set(); - for (let i = 0; i < 100000; i++) set.add(hash(i)); - expect(set.size).toBe(100000); -}); diff --git a/packages/json-joy/src/json-hash/hash.ts b/packages/json-joy/src/json-hash/hash.ts index c3a778e55c..c4716fb86d 100644 --- a/packages/json-joy/src/json-hash/hash.ts +++ b/packages/json-joy/src/json-hash/hash.ts @@ -1,70 +1 @@ -import {sort} from '@jsonjoy.com/util/lib/sort/insertion'; -import type {PackValue} from '@jsonjoy.com/json-pack/lib/types'; - -export enum CONST { - START_STATE = 5381, - - NULL = 982452847, - TRUE = 982453247, - FALSE = 982454243, - ARRAY = 982452259, - STRING = 982453601, - OBJECT = 982454533, - BINARY = 982454837, -} - -export const updateNum = (state: number, num: number): number => { - return (state << 5) + state + num; -}; - -export const updateStr = (state: number, str: string): number => { - const length = str.length; - state = updateNum(state, CONST.STRING); - state = updateNum(state, length); - let i = length; - while (i) state = (state << 5) + state + str.charCodeAt(--i); - return state; -}; - -export const updateBin = (state: number, bin: Uint8Array): number => { - const length = bin.length; - state = updateNum(state, CONST.BINARY); - state = updateNum(state, length); - let i = length; - while (i) state = (state << 5) + state + bin[--i]; - return state; -}; - -export const updateJson = (state: number, json: unknown): number => { - switch (typeof json) { - case 'number': - return updateNum(state, json); - case 'string': - state = updateNum(state, CONST.STRING); - return updateStr(state, json); - case 'object': { - if (json === null) return updateNum(state, CONST.NULL); - if (Array.isArray(json)) { - const length = json.length; - state = updateNum(state, CONST.ARRAY); - for (let i = 0; i < length; i++) state = updateJson(state, json[i]); - return state; - } - if (json instanceof Uint8Array) return updateBin(state, json); - state = updateNum(state, CONST.OBJECT); - const keys = sort(Object.keys(json as object)); - const length = keys.length; - for (let i = 0; i < length; i++) { - const key = keys[i]; - state = updateStr(state, key); - state = updateJson(state, (json as any)[key]); - } - return state; - } - case 'boolean': - return updateNum(state, json ? CONST.TRUE : CONST.FALSE); - } - return state; -}; - -export const hash = (json: PackValue) => updateJson(CONST.START_STATE, json) >>> 0; +export * from '@jsonjoy.com/json-hash'; diff --git a/packages/json-joy/src/json-hash/structHash.ts b/packages/json-joy/src/json-hash/structHash.ts index 2d2a8798b0..ac8e0ac778 100644 --- a/packages/json-joy/src/json-hash/structHash.ts +++ b/packages/json-joy/src/json-hash/structHash.ts @@ -1,5 +1,5 @@ import {sort} from '@jsonjoy.com/util/lib/sort/insertion'; -import {hash} from './hash'; +import {hash} from '@jsonjoy.com/json-hash'; import {Timestamp} from '../json-crdt-patch'; /** diff --git a/packages/json-joy/src/json-hash/structHashCrdt.ts b/packages/json-joy/src/json-hash/structHashCrdt.ts index 7aa7556bb9..8dbff67417 100644 --- a/packages/json-joy/src/json-hash/structHashCrdt.ts +++ b/packages/json-joy/src/json-hash/structHashCrdt.ts @@ -1,6 +1,6 @@ import {sort} from '@jsonjoy.com/util/lib/sort/insertion'; import {ArrNode, BinNode, ConNode, type JsonNode, ObjNode, StrNode, ValNode, VecNode} from '../json-crdt/nodes'; -import {hash} from './hash'; +import {hash} from '@jsonjoy.com/json-hash'; import {structHash} from './structHash'; /** diff --git a/packages/json-joy/src/json-hash/structHashSchema.ts b/packages/json-joy/src/json-hash/structHashSchema.ts index 0936864792..31ffba0fca 100644 --- a/packages/json-joy/src/json-hash/structHashSchema.ts +++ b/packages/json-joy/src/json-hash/structHashSchema.ts @@ -1,6 +1,6 @@ import {sort} from '@jsonjoy.com/util/lib/sort/insertion'; import {nodes, type SchemaNode} from '../json-crdt-patch/schema'; -import {hash} from './hash'; +import {hash} from '@jsonjoy.com/json-hash'; import {structHash} from './structHash'; export const structHashSchema = (node?: SchemaNode | unknown): string => { diff --git a/packages/json-joy/tsconfig.build.json b/packages/json-joy/tsconfig.build.json index 04db9ebc55..1974798fc8 100644 --- a/packages/json-joy/tsconfig.build.json +++ b/packages/json-joy/tsconfig.build.json @@ -35,6 +35,9 @@ { "path": "../json-equal/tsconfig.build.json" }, + { + "path": "../json-hash/tsconfig.build.json" + }, { "path": "../json-pack/tsconfig.build.json" }, diff --git a/packages/json-joy/tsconfig.json b/packages/json-joy/tsconfig.json index 30a38f80c1..1cb6955a0e 100644 --- a/packages/json-joy/tsconfig.json +++ b/packages/json-joy/tsconfig.json @@ -20,6 +20,9 @@ { "path": "../json-equal" }, + { + "path": "../json-hash" + }, { "path": "../json-pack" }, From 9d1941893cc055ea8f268e38e5636bcfcbc28ba5 Mon Sep 17 00:00:00 2001 From: streamich Date: Mon, 6 Jul 2026 16:46:22 +0200 Subject: [PATCH 05/14] =?UTF-8?q?feat:=20=F0=9F=8E=B8=20move=20structural?= =?UTF-8?q?=20hashes=20to=20their=20right=20places?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/json-joy/src/json-crdt-diff/JsonCrdtDiff.ts | 4 ++-- .../__tests__/assertStructHash.ts | 2 +- .../__tests__/structHash-automated.spec.ts | 0 .../__tests__/structHash-fuzzing.spec.ts | 0 .../__tests__/structHashCrdt.spec.ts | 0 .../src/{json-hash => json-crdt-diff}/structHashCrdt.ts | 2 +- .../src/{json-hash => json-crdt-diff}/structHashSchema.ts | 2 +- .../__tests__/structHash.spec.ts | 2 +- .../json-joy/src/{json-hash => json-crdt-patch}/structHash.ts | 2 +- packages/json-joy/src/json-hash/index.ts | 1 - packages/json-joy/src/json-patch-diff/JsonPatchDiff.ts | 2 +- 11 files changed, 8 insertions(+), 9 deletions(-) rename packages/json-joy/src/{json-hash => json-crdt-diff}/__tests__/assertStructHash.ts (91%) rename packages/json-joy/src/{json-hash => json-crdt-diff}/__tests__/structHash-automated.spec.ts (100%) rename packages/json-joy/src/{json-hash => json-crdt-diff}/__tests__/structHash-fuzzing.spec.ts (100%) rename packages/json-joy/src/{json-hash => json-crdt-diff}/__tests__/structHashCrdt.spec.ts (100%) rename packages/json-joy/src/{json-hash => json-crdt-diff}/structHashCrdt.ts (96%) rename packages/json-joy/src/{json-hash => json-crdt-diff}/structHashSchema.ts (95%) rename packages/json-joy/src/{json-hash => json-crdt-patch}/__tests__/structHash.spec.ts (98%) rename packages/json-joy/src/{json-hash => json-crdt-patch}/structHash.ts (97%) diff --git a/packages/json-joy/src/json-crdt-diff/JsonCrdtDiff.ts b/packages/json-joy/src/json-crdt-diff/JsonCrdtDiff.ts index 2d4f713897..f2ecbcd384 100644 --- a/packages/json-joy/src/json-crdt-diff/JsonCrdtDiff.ts +++ b/packages/json-joy/src/json-crdt-diff/JsonCrdtDiff.ts @@ -14,8 +14,8 @@ import {ArrNode, BinNode, ConNode, ObjNode, StrNode, ValNode, VecNode, type Json import * as str from '../util/diff/str'; import * as bin from '../util/diff/bin'; import * as line from '../util/diff/line'; -import {structHashCrdt} from '../json-hash/structHashCrdt'; -import {structHashSchema} from '../json-hash/structHashSchema'; +import {structHashCrdt} from './structHashCrdt'; +import {structHashSchema} from './structHashSchema'; import type {Model} from '../json-crdt/model'; export class DiffError extends Error { diff --git a/packages/json-joy/src/json-hash/__tests__/assertStructHash.ts b/packages/json-joy/src/json-crdt-diff/__tests__/assertStructHash.ts similarity index 91% rename from packages/json-joy/src/json-hash/__tests__/assertStructHash.ts rename to packages/json-joy/src/json-crdt-diff/__tests__/assertStructHash.ts index 9aa3debf51..2a18b523dd 100644 --- a/packages/json-joy/src/json-hash/__tests__/assertStructHash.ts +++ b/packages/json-joy/src/json-crdt-diff/__tests__/assertStructHash.ts @@ -1,4 +1,4 @@ -import {structHash as structHash_} from '../structHash'; +import {structHash as structHash_} from '../../json-crdt-patch/structHash'; import {structHashCrdt} from '../structHashCrdt'; import {structHashSchema} from '../structHashSchema'; import {Model} from '../../json-crdt'; diff --git a/packages/json-joy/src/json-hash/__tests__/structHash-automated.spec.ts b/packages/json-joy/src/json-crdt-diff/__tests__/structHash-automated.spec.ts similarity index 100% rename from packages/json-joy/src/json-hash/__tests__/structHash-automated.spec.ts rename to packages/json-joy/src/json-crdt-diff/__tests__/structHash-automated.spec.ts diff --git a/packages/json-joy/src/json-hash/__tests__/structHash-fuzzing.spec.ts b/packages/json-joy/src/json-crdt-diff/__tests__/structHash-fuzzing.spec.ts similarity index 100% rename from packages/json-joy/src/json-hash/__tests__/structHash-fuzzing.spec.ts rename to packages/json-joy/src/json-crdt-diff/__tests__/structHash-fuzzing.spec.ts diff --git a/packages/json-joy/src/json-hash/__tests__/structHashCrdt.spec.ts b/packages/json-joy/src/json-crdt-diff/__tests__/structHashCrdt.spec.ts similarity index 100% rename from packages/json-joy/src/json-hash/__tests__/structHashCrdt.spec.ts rename to packages/json-joy/src/json-crdt-diff/__tests__/structHashCrdt.spec.ts diff --git a/packages/json-joy/src/json-hash/structHashCrdt.ts b/packages/json-joy/src/json-crdt-diff/structHashCrdt.ts similarity index 96% rename from packages/json-joy/src/json-hash/structHashCrdt.ts rename to packages/json-joy/src/json-crdt-diff/structHashCrdt.ts index 8dbff67417..f8307e70e7 100644 --- a/packages/json-joy/src/json-hash/structHashCrdt.ts +++ b/packages/json-joy/src/json-crdt-diff/structHashCrdt.ts @@ -1,7 +1,7 @@ import {sort} from '@jsonjoy.com/util/lib/sort/insertion'; import {ArrNode, BinNode, ConNode, type JsonNode, ObjNode, StrNode, ValNode, VecNode} from '../json-crdt/nodes'; import {hash} from '@jsonjoy.com/json-hash'; -import {structHash} from './structHash'; +import {structHash} from '../json-crdt-patch/structHash'; /** * Constructs a structural hash of the view of the node. diff --git a/packages/json-joy/src/json-hash/structHashSchema.ts b/packages/json-joy/src/json-crdt-diff/structHashSchema.ts similarity index 95% rename from packages/json-joy/src/json-hash/structHashSchema.ts rename to packages/json-joy/src/json-crdt-diff/structHashSchema.ts index 31ffba0fca..ac036c568a 100644 --- a/packages/json-joy/src/json-hash/structHashSchema.ts +++ b/packages/json-joy/src/json-crdt-diff/structHashSchema.ts @@ -1,7 +1,7 @@ import {sort} from '@jsonjoy.com/util/lib/sort/insertion'; import {nodes, type SchemaNode} from '../json-crdt-patch/schema'; import {hash} from '@jsonjoy.com/json-hash'; -import {structHash} from './structHash'; +import {structHash} from '../json-crdt-patch/structHash'; export const structHashSchema = (node?: SchemaNode | unknown): string => { if (node instanceof nodes.con || node instanceof nodes.str || node instanceof nodes.bin) return structHash(node.raw); diff --git a/packages/json-joy/src/json-hash/__tests__/structHash.spec.ts b/packages/json-joy/src/json-crdt-patch/__tests__/structHash.spec.ts similarity index 98% rename from packages/json-joy/src/json-hash/__tests__/structHash.spec.ts rename to packages/json-joy/src/json-crdt-patch/__tests__/structHash.spec.ts index 1084832575..932fe21eec 100644 --- a/packages/json-joy/src/json-hash/__tests__/structHash.spec.ts +++ b/packages/json-joy/src/json-crdt-patch/__tests__/structHash.spec.ts @@ -1,7 +1,7 @@ import {clone} from '@jsonjoy.com/util/lib/json-clone'; import {structHash as structHash_} from '../structHash'; import {RandomJson} from '@jsonjoy.com/json-random'; -import {ts} from '../../json-crdt-patch'; +import {ts} from '../clock'; const isASCII = (str: string) => /^[\x00-\x7F]*$/.test(str); diff --git a/packages/json-joy/src/json-hash/structHash.ts b/packages/json-joy/src/json-crdt-patch/structHash.ts similarity index 97% rename from packages/json-joy/src/json-hash/structHash.ts rename to packages/json-joy/src/json-crdt-patch/structHash.ts index ac8e0ac778..5dabf323e8 100644 --- a/packages/json-joy/src/json-hash/structHash.ts +++ b/packages/json-joy/src/json-crdt-patch/structHash.ts @@ -1,6 +1,6 @@ import {sort} from '@jsonjoy.com/util/lib/sort/insertion'; import {hash} from '@jsonjoy.com/json-hash'; -import {Timestamp} from '../json-crdt-patch'; +import {Timestamp} from './clock'; /** * Produces a *structural hash* of a JSON value. diff --git a/packages/json-joy/src/json-hash/index.ts b/packages/json-joy/src/json-hash/index.ts index 6d361c7ea8..6719163c39 100644 --- a/packages/json-joy/src/json-hash/index.ts +++ b/packages/json-joy/src/json-hash/index.ts @@ -1,2 +1 @@ export * from './hash'; -export * from './structHash'; diff --git a/packages/json-joy/src/json-patch-diff/JsonPatchDiff.ts b/packages/json-joy/src/json-patch-diff/JsonPatchDiff.ts index 29badd174c..52e779d128 100644 --- a/packages/json-joy/src/json-patch-diff/JsonPatchDiff.ts +++ b/packages/json-joy/src/json-patch-diff/JsonPatchDiff.ts @@ -1,7 +1,7 @@ import {deepEqual} from '@jsonjoy.com/util/lib/json-equal/deepEqual'; import * as str from '../util/diff/str'; import * as line from '../util/diff/line'; -import {structHash} from '../json-hash'; +import {structHash} from '../json-crdt-patch/structHash'; import {escapeComponent} from '@jsonjoy.com/json-pointer/lib/util'; import type {Operation} from '../json-patch/codec/json/types'; From fe57b2cc776f3e3e87485fc39d5e63a27589e394 Mon Sep 17 00:00:00 2001 From: streamich Date: Mon, 6 Jul 2026 17:16:37 +0200 Subject: [PATCH 06/14] =?UTF-8?q?feat:=20=F0=9F=8E=B8=20improve=20crdt=20s?= =?UTF-8?q?tore=20implementation?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../json-crdt-server/__tests__/setup.ts | 16 ++++++++++++++-- .../services/blocks/store/level/LevelStore.ts | 2 +- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/packages/rpc-server/src/__demos__/json-crdt-server/__tests__/setup.ts b/packages/rpc-server/src/__demos__/json-crdt-server/__tests__/setup.ts index 273267ba59..6e90c84106 100644 --- a/packages/rpc-server/src/__demos__/json-crdt-server/__tests__/setup.ts +++ b/packages/rpc-server/src/__demos__/json-crdt-server/__tests__/setup.ts @@ -1,3 +1,6 @@ +import {mkdtempSync, rmSync} from 'fs'; +import {tmpdir} from 'os'; +import {join} from 'path'; import {MemoryLevel} from 'memory-level'; import {CalleeCaller} from '@jsonjoy.com/rpc-calls/lib/caller/CalleeCaller'; import {createCaller} from '../routes'; @@ -46,10 +49,19 @@ export const setupLevelMemory = async () => { }; export const setupLevelClassic = async () => { - const kv = new ClassicLevel('./db', {valueEncoding: 'view'}); + // Use a unique temp directory per setup so each test is fully isolated: no + // shared state or leftover data across tests/runs, and no `LOCK already held` + // contention if one test fails before it can close its database. + const dir = mkdtempSync(join(tmpdir(), 'json-crdt-server-level-')); + const kv = new ClassicLevel(dir, {valueEncoding: 'view'}); await kv.open(); const store = new LevelStore(kv); - return setup(store, async () => kv.close()); + return setup(store, async () => { + await kv.close(); + try { + rmSync(dir, {recursive: true, force: true}); + } catch {} + }); }; export type JsonCrdtTestSetup = typeof setup; diff --git a/packages/rpc-server/src/__demos__/json-crdt-server/services/blocks/store/level/LevelStore.ts b/packages/rpc-server/src/__demos__/json-crdt-server/services/blocks/store/level/LevelStore.ts index 84a11355e7..d8d4d355c0 100644 --- a/packages/rpc-server/src/__demos__/json-crdt-server/services/blocks/store/level/LevelStore.ts +++ b/packages/rpc-server/src/__demos__/json-crdt-server/services/blocks/store/level/LevelStore.ts @@ -95,7 +95,7 @@ export class LevelStore implements types.Store { public async seq(id: string): Promise { return await this.mutex.acquire(id, async () => { const base = this.batchBase(id); - const keys = await this.kv.keys({lt: base + '~', limit: 1, reverse: true}).all(); + const keys = await this.kv.keys({gte: base, lt: base + '~', limit: 1, reverse: true}).all(); if (!keys || keys.length < 1) return; const key = keys[0].slice(base.length); if (!key) return; From 55d623a35403e564d2b337415c3d47c388e7eaf3 Mon Sep 17 00:00:00 2001 From: streamich Date: Mon, 6 Jul 2026 17:32:30 +0200 Subject: [PATCH 07/14] =?UTF-8?q?fix:=20=F0=9F=90=9B=20harden=20failure=20?= =?UTF-8?q?capture?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../json-crdt-repo/src/session/EditSession.ts | 26 ++++++++++------ .../__tests__/EditSession.delrace.spec.ts | 31 +++++++++++++++++++ 2 files changed, 48 insertions(+), 9 deletions(-) create mode 100644 packages/json-crdt-repo/src/session/__tests__/EditSession.delrace.spec.ts diff --git a/packages/json-crdt-repo/src/session/EditSession.ts b/packages/json-crdt-repo/src/session/EditSession.ts index edbf6fc0f7..b761e99f1e 100644 --- a/packages/json-crdt-repo/src/session/EditSession.ts +++ b/packages/json-crdt-repo/src/session/EditSession.ts @@ -120,15 +120,23 @@ export class EditSession> { const cursorBehind = this.cursor !== res.cursor; if (cursorBehind) { const timer = setTimeout(async () => { - if (this._stopped) return; - const get = await this.repo.getIf({ - id: this.id, - cursor: this.cursor, - }); - if (this._stopped) return; - if (!get) return; - this.reset(get.model); - this.cursor = get.cursor; + try { + if (this._stopped) return; + const get = await this.repo.getIf({ + id: this.id, + cursor: this.cursor, + }); + if (this._stopped) return; + if (!get) return; + this.reset(get.model); + this.cursor = get.cursor; + } catch { + // Best-effort catch-up in a detached timer. The block may have + // been deleted (getIf throws "NotFound") or the repo stopped + // between scheduling and firing. Deletion is handled via the + // change$/onEvent delete flow, so swallow the error here instead + // of letting it surface as an unhandled promise rejection. + } }, 50); (timer as {unref?: () => void}).unref?.(); } diff --git a/packages/json-crdt-repo/src/session/__tests__/EditSession.delrace.spec.ts b/packages/json-crdt-repo/src/session/__tests__/EditSession.delrace.spec.ts new file mode 100644 index 0000000000..e2be410e49 --- /dev/null +++ b/packages/json-crdt-repo/src/session/__tests__/EditSession.delrace.spec.ts @@ -0,0 +1,31 @@ +import {s} from 'json-joy/lib/json-crdt'; +import {tick} from 'thingies'; +import {BehaviorSubject} from 'rxjs'; +import {Testbed} from '../../__tests__/testbed'; + +describe('.del() catch-up timer race', () => { + test('deleting a block does not throw from a pending catch-up timer', async () => { + const rejections: unknown[] = []; + const onRej = (err: unknown) => rejections.push(err); + process.on('unhandledRejection', onRej); + try { + const repo = Testbed.createRepo({connected$: new BehaviorSubject(false)}); + const schema = s.obj({id: s.con('asdf')}); + const {session} = repo.sessions.make({id: repo.blockId, schema}); + await session.sync(); + const session2 = await repo.sessions.load({id: repo.blockId}); + await session2.del(); + await tick(120); + await session.dispose(); + await session2.dispose(); + await repo.stopTab(); + await tick(10); + const notFound = rejections.filter( + (e) => (e as any)?.code === 'LEVEL_NOT_FOUND' || /not.?found/i.test(String((e as any)?.message ?? e)), + ); + expect(notFound).toEqual([]); + } finally { + process.off('unhandledRejection', onRej); + } + }); +}); From 12a83e6c676abcc28acfe0e6f119d75853c10ee9 Mon Sep 17 00:00:00 2001 From: streamich Date: Tue, 7 Jul 2026 14:25:13 +0200 Subject: [PATCH 08/14] =?UTF-8?q?feat:=20=F0=9F=8E=B8=20move=20print=20uti?= =?UTF-8?q?ls=20under=20patch=20module?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/json-joy/src/{util => json-crdt-patch}/print.ts | 2 +- packages/json-joy/src/json-crdt-patch/schema.ts | 2 +- packages/json-joy/src/json-crdt/delta/Delta.ts | 2 +- packages/json-joy/src/json-crdt/model/Model.ts | 2 +- packages/json-joy/src/json-crdt/nodes/const/ConNode.ts | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) rename packages/json-joy/src/{util => json-crdt-patch}/print.ts (90%) diff --git a/packages/json-joy/src/util/print.ts b/packages/json-joy/src/json-crdt-patch/print.ts similarity index 90% rename from packages/json-joy/src/util/print.ts rename to packages/json-joy/src/json-crdt-patch/print.ts index 21fd44ef57..f94b1c7978 100644 --- a/packages/json-joy/src/util/print.ts +++ b/packages/json-joy/src/json-crdt-patch/print.ts @@ -1,5 +1,5 @@ import {toLine} from 'pojo-dump/lib/toLine'; -import {printTs, Timestamp} from '../json-crdt-patch'; +import {printTs, Timestamp} from './clock'; export const line = toLine; diff --git a/packages/json-joy/src/json-crdt-patch/schema.ts b/packages/json-joy/src/json-crdt-patch/schema.ts index cfad45a2da..06810b787c 100644 --- a/packages/json-joy/src/json-crdt-patch/schema.ts +++ b/packages/json-joy/src/json-crdt-patch/schema.ts @@ -1,6 +1,6 @@ import {isUint8Array} from '@jsonjoy.com/buffers/lib/isUint8Array'; import {Timestamp, type ITimestampStruct} from './clock'; -import * as print from '../util/print'; +import * as print from './print'; import {printTree, type Printable} from 'tree-dump'; import type {PatchBuilder} from './PatchBuilder'; diff --git a/packages/json-joy/src/json-crdt/delta/Delta.ts b/packages/json-joy/src/json-crdt/delta/Delta.ts index 3a1d5fb7fb..e049238f4a 100644 --- a/packages/json-joy/src/json-crdt/delta/Delta.ts +++ b/packages/json-joy/src/json-crdt/delta/Delta.ts @@ -2,7 +2,7 @@ import {printTree} from 'tree-dump'; import type {Batch} from '../../json-crdt-patch/Batch'; import type {IClockVector} from '../../json-crdt-patch'; import {encoder, decoder} from './codec/binary/shared'; -import {indent} from '../../util/print'; +import {indent} from '../../json-crdt-patch/print'; import type {Printable} from 'tree-dump/lib/types'; import type {JsonCrdtOperation} from '../../json-crdt-patch/operations'; diff --git a/packages/json-joy/src/json-crdt/model/Model.ts b/packages/json-joy/src/json-crdt/model/Model.ts index c37d2b7dd1..11d460a341 100644 --- a/packages/json-joy/src/json-crdt/model/Model.ts +++ b/packages/json-joy/src/json-crdt/model/Model.ts @@ -11,7 +11,7 @@ import {Extensions} from '../extensions/Extensions'; import {AvlMap} from 'sonic-forest/lib/avl/AvlMap'; import {NodeBuilder, type nodes, s} from '../../json-crdt-patch'; import {cmpNode} from '../equal/cmpNode'; -import {indent} from '../../util/print'; +import {indent} from '../../json-crdt-patch/print'; import {Delta, type DeltaMutator} from '../delta/Delta'; import {Batch} from '../../json-crdt-patch/Batch'; import {type JsonCrdtPatchOperation, Patch} from '../../json-crdt-patch/Patch'; diff --git a/packages/json-joy/src/json-crdt/nodes/const/ConNode.ts b/packages/json-joy/src/json-crdt/nodes/const/ConNode.ts index 38f80549b9..48d7a16296 100644 --- a/packages/json-joy/src/json-crdt/nodes/const/ConNode.ts +++ b/packages/json-joy/src/json-crdt/nodes/const/ConNode.ts @@ -1,4 +1,4 @@ -import {con as printCon} from '../../../util/print'; +import {con as printCon} from '../../../json-crdt-patch/print'; import {NewConOp} from '../../../json-crdt-patch'; import {type IClockVector, type ITimestampStruct, printTs, Timestamp} from '../../../json-crdt-patch/clock'; import type {Model} from '../../model'; From 2275c0a84c533642f4bf10d9877ee640e01f6423 Mon Sep 17 00:00:00 2001 From: streamich Date: Tue, 7 Jul 2026 14:35:49 +0200 Subject: [PATCH 09/14] =?UTF-8?q?refactor:=20=F0=9F=92=A1=20move=20iterato?= =?UTF-8?q?r=20helpers=20to=20utils=20package?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../json-joy/src/json-crdt-extensions/peritext/block/Block.ts | 2 +- .../json-joy/src/json-crdt-extensions/peritext/editor/Editor.ts | 2 +- .../json-joy/src/json-crdt-extensions/peritext/editor/types.ts | 2 +- .../src/json-crdt-extensions/peritext/overlay/Overlay.ts | 2 +- .../peritext/overlay/__tests__/Overlay.markers.spec.ts | 2 +- .../json-joy/src/json-crdt-extensions/peritext/slice/Slices.ts | 2 +- packages/json-joy/src/json-crdt/nodes/rga/AbstractRga.ts | 2 +- packages/json-joy/src/json-ml/walk.ts | 2 +- packages/{json-joy/src/util => util/src}/iterator/index.ts | 0 packages/{json-joy/src/util => util/src}/iterator/polyfill.ts | 0 10 files changed, 8 insertions(+), 8 deletions(-) rename packages/{json-joy/src/util => util/src}/iterator/index.ts (100%) rename packages/{json-joy/src/util => util/src}/iterator/polyfill.ts (100%) diff --git a/packages/json-joy/src/json-crdt-extensions/peritext/block/Block.ts b/packages/json-joy/src/json-crdt-extensions/peritext/block/Block.ts index 5f5c27974b..43b577d028 100644 --- a/packages/json-joy/src/json-crdt-extensions/peritext/block/Block.ts +++ b/packages/json-joy/src/json-crdt-extensions/peritext/block/Block.ts @@ -1,6 +1,6 @@ import {printTree} from 'tree-dump/lib/printTree'; import {CONST, updateJson, updateNum} from '@jsonjoy.com/json-hash'; -import {UndEndIterator, type UndEndNext} from '../../../util/iterator'; +import {UndEndIterator, type UndEndNext} from '@jsonjoy.com/util/lib/iterator'; import {Inline} from './Inline'; import {formatStep, getTag} from '../slice/util'; import {Range} from '../rga/Range'; diff --git a/packages/json-joy/src/json-crdt-extensions/peritext/editor/Editor.ts b/packages/json-joy/src/json-crdt-extensions/peritext/editor/Editor.ts index 11075dd752..0eef28ba13 100644 --- a/packages/json-joy/src/json-crdt-extensions/peritext/editor/Editor.ts +++ b/packages/json-joy/src/json-crdt-extensions/peritext/editor/Editor.ts @@ -10,7 +10,7 @@ import {toLine} from 'pojo-dump/lib/toLine'; import {CommonSliceType, type SliceTypeSteps, type SliceType, type SliceTypeStep} from '../slice'; import {isLetter, isPunctuation, isWhitespace, stepsEqual} from './util'; import {Value} from '../../../util/events/sync-store'; -import {UndEndIterator, type UndEndNext} from '../../../util/iterator'; +import {UndEndIterator, type UndEndNext} from '@jsonjoy.com/util/lib/iterator'; import { type Patch, tick, diff --git a/packages/json-joy/src/json-crdt-extensions/peritext/editor/types.ts b/packages/json-joy/src/json-crdt-extensions/peritext/editor/types.ts index e2783f7fd0..95b9eae605 100644 --- a/packages/json-joy/src/json-crdt-extensions/peritext/editor/types.ts +++ b/packages/json-joy/src/json-crdt-extensions/peritext/editor/types.ts @@ -1,4 +1,4 @@ -import type {UndEndNext} from '../../../util/iterator'; +import type {UndEndNext} from '@jsonjoy.com/util/lib/iterator'; import type {Point} from '../rga/Point'; import type {Range} from '../rga/Range'; import type {SliceType} from '../slice'; diff --git a/packages/json-joy/src/json-crdt-extensions/peritext/overlay/Overlay.ts b/packages/json-joy/src/json-crdt-extensions/peritext/overlay/Overlay.ts index e587f1d6df..14d1148e1b 100644 --- a/packages/json-joy/src/json-crdt-extensions/peritext/overlay/Overlay.ts +++ b/packages/json-joy/src/json-crdt-extensions/peritext/overlay/Overlay.ts @@ -8,7 +8,7 @@ import {OverlayPoint} from './OverlayPoint'; import {compare, type ITimestampStruct} from '../../../json-crdt-patch/clock'; import {CONST, updateNum} from '@jsonjoy.com/json-hash'; import {Slice} from '../slice/Slice'; -import {UndEndIterator, type UndEndNext} from '../../../util/iterator'; +import {UndEndIterator, type UndEndNext} from '@jsonjoy.com/util/lib/iterator'; import {SliceStacking} from '../slice/constants'; import {OverlayRefSliceStart} from './refs'; import type {Point} from '../rga/Point'; diff --git a/packages/json-joy/src/json-crdt-extensions/peritext/overlay/__tests__/Overlay.markers.spec.ts b/packages/json-joy/src/json-crdt-extensions/peritext/overlay/__tests__/Overlay.markers.spec.ts index 9899198e63..ef3b567f64 100644 --- a/packages/json-joy/src/json-crdt-extensions/peritext/overlay/__tests__/Overlay.markers.spec.ts +++ b/packages/json-joy/src/json-crdt-extensions/peritext/overlay/__tests__/Overlay.markers.spec.ts @@ -1,4 +1,4 @@ -import {UndEndIterator} from '../../../../util/iterator'; +import {UndEndIterator} from '@jsonjoy.com/util/lib/iterator'; import {type Kit, runNumbersKitTestSuite} from '../../__tests__/setup'; import type {Point} from '../../rga/Point'; import {OverlayPoint} from '../OverlayPoint'; diff --git a/packages/json-joy/src/json-crdt-extensions/peritext/slice/Slices.ts b/packages/json-joy/src/json-crdt-extensions/peritext/slice/Slices.ts index 28251443b3..f277b51919 100644 --- a/packages/json-joy/src/json-crdt-extensions/peritext/slice/Slices.ts +++ b/packages/json-joy/src/json-crdt-extensions/peritext/slice/Slices.ts @@ -7,7 +7,7 @@ import {CONST, updateNum} from '@jsonjoy.com/json-hash'; import {SliceHeaderShift, SliceStacking, SliceTupleIndex} from './constants'; import {VecNode} from '../../../json-crdt/nodes'; import {Anchor} from '../rga/constants'; -import {UndEndIterator, type UndEndNext} from '../../../util/iterator'; +import {UndEndIterator, type UndEndNext} from '@jsonjoy.com/util/lib/iterator'; import * as schema from './schema'; import type {Range} from '../rga/Range'; import type {SliceType} from './types'; diff --git a/packages/json-joy/src/json-crdt/nodes/rga/AbstractRga.ts b/packages/json-joy/src/json-crdt/nodes/rga/AbstractRga.ts index d46b4797e4..29cc03a2b2 100644 --- a/packages/json-joy/src/json-crdt/nodes/rga/AbstractRga.ts +++ b/packages/json-joy/src/json-crdt/nodes/rga/AbstractRga.ts @@ -16,7 +16,7 @@ import {insert2, remove2} from 'sonic-forest/lib/util2'; import {ORIGIN} from '../../../json-crdt-patch/constants'; import {printTree} from 'tree-dump/lib/printTree'; import {printBinary} from 'tree-dump/lib/printBinary'; -import {UndEndIterator, type UndEndNext} from '../../../util/iterator'; +import {UndEndIterator, type UndEndNext} from '@jsonjoy.com/util/lib/iterator'; /** * @category CRDT Node diff --git a/packages/json-joy/src/json-ml/walk.ts b/packages/json-joy/src/json-ml/walk.ts index 5209febfa4..624e7b92e3 100644 --- a/packages/json-joy/src/json-ml/walk.ts +++ b/packages/json-joy/src/json-ml/walk.ts @@ -1,4 +1,4 @@ -import {UndEndIterator, type UndEndNext} from '../util/iterator'; +import {UndEndIterator, type UndEndNext} from '@jsonjoy.com/util/lib/iterator'; import type {JsonMlNode} from './types'; export const walk0 = (node: JsonMlNode): UndEndNext => { diff --git a/packages/json-joy/src/util/iterator/index.ts b/packages/util/src/iterator/index.ts similarity index 100% rename from packages/json-joy/src/util/iterator/index.ts rename to packages/util/src/iterator/index.ts diff --git a/packages/json-joy/src/util/iterator/polyfill.ts b/packages/util/src/iterator/polyfill.ts similarity index 100% rename from packages/json-joy/src/util/iterator/polyfill.ts rename to packages/util/src/iterator/polyfill.ts From 94493b6701d8b8462bd637f15525e433b3f54867 Mon Sep 17 00:00:00 2001 From: streamich Date: Tue, 7 Jul 2026 14:40:25 +0200 Subject: [PATCH 10/14] =?UTF-8?q?refactor:=20=F0=9F=92=A1=20import=20sync?= =?UTF-8?q?=20store=20utils=20directly=20from=20`"thingies"`?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/collaborative-react/package.json | 3 ++- packages/collaborative-react/src/hooks.ts | 2 +- .../src/json-crdt-extensions/peritext/editor/Editor.ts | 2 +- packages/json-joy/src/json-crdt/json-patch/JsonPatchStore.ts | 2 +- packages/json-joy/src/json-crdt/model/api/NodeEvents.ts | 2 +- packages/json-joy/src/json-crdt/model/api/nodes.ts | 2 +- packages/json-joy/src/util/events/sync-store.ts | 1 - packages/peritext/package.json | 3 ++- packages/peritext/src/editor/state/menus/CaretMenu.tsx | 2 +- packages/peritext/src/plugins/debug/RenderPeritext.tsx | 2 +- packages/peritext/src/plugins/debug/context.ts | 2 +- packages/peritext/src/plugins/debug/state/index.tsx | 2 +- packages/peritext/src/plugins/minimal/RenderPeritext.tsx | 2 +- packages/peritext/src/plugins/minimal/context.ts | 2 +- packages/peritext/src/web/react/hooks.ts | 2 +- packages/peritext/src/web/state/index.ts | 2 +- yarn.lock | 2 ++ 17 files changed, 19 insertions(+), 16 deletions(-) delete mode 100644 packages/json-joy/src/util/events/sync-store.ts diff --git a/packages/collaborative-react/package.json b/packages/collaborative-react/package.json index 693212f1e7..6dca9b7263 100644 --- a/packages/collaborative-react/package.json +++ b/packages/collaborative-react/package.json @@ -32,7 +32,8 @@ "crdt" ], "dependencies": { - "json-joy": "workspace:*" + "json-joy": "workspace:*", + "thingies": "^2.6.0" }, "peerDependencies": { "react": "^19", diff --git a/packages/collaborative-react/src/hooks.ts b/packages/collaborative-react/src/hooks.ts index 616bd86fc6..7844936d2c 100644 --- a/packages/collaborative-react/src/hooks.ts +++ b/packages/collaborative-react/src/hooks.ts @@ -1,7 +1,7 @@ import {useState, useMemo, useCallback, useSyncExternalStore, useEffect} from 'react'; import {useCtxModelStrict, useCtxNodeStrict} from './context'; import type {FanOutUnsubscribe} from 'thingies/lib/fanout'; -import type {SyncStore} from 'json-joy/lib/util/events/sync-store'; +import type {SyncStore} from 'thingies/lib/sync'; import type {Model, JsonNodeView, ArrApi, ObjApi, StrApi} from 'json-joy/lib/json-crdt'; import type {ChangeEvent} from 'json-joy/lib/json-crdt/model/api/events'; import type {ApiPath} from 'json-joy/lib/json-crdt/model/api/types'; diff --git a/packages/json-joy/src/json-crdt-extensions/peritext/editor/Editor.ts b/packages/json-joy/src/json-crdt-extensions/peritext/editor/Editor.ts index 0eef28ba13..51fce50db0 100644 --- a/packages/json-joy/src/json-crdt-extensions/peritext/editor/Editor.ts +++ b/packages/json-joy/src/json-crdt-extensions/peritext/editor/Editor.ts @@ -9,7 +9,7 @@ import {Slice} from '../slice/Slice'; import {toLine} from 'pojo-dump/lib/toLine'; import {CommonSliceType, type SliceTypeSteps, type SliceType, type SliceTypeStep} from '../slice'; import {isLetter, isPunctuation, isWhitespace, stepsEqual} from './util'; -import {Value} from '../../../util/events/sync-store'; +import {Value} from 'thingies/lib/sync'; import {UndEndIterator, type UndEndNext} from '@jsonjoy.com/util/lib/iterator'; import { type Patch, diff --git a/packages/json-joy/src/json-crdt/json-patch/JsonPatchStore.ts b/packages/json-joy/src/json-crdt/json-patch/JsonPatchStore.ts index cd88e7d8a8..62a0fd6d62 100644 --- a/packages/json-joy/src/json-crdt/json-patch/JsonPatchStore.ts +++ b/packages/json-joy/src/json-crdt/json-patch/JsonPatchStore.ts @@ -1,4 +1,4 @@ -import type {SyncStore} from '../../util/events/sync-store'; +import type {SyncStore} from 'thingies/lib/sync'; import type {JsonNodeApi} from '../model/api/types'; import {JsonPatch} from './JsonPatch'; import {toPath} from '@jsonjoy.com/json-pointer/lib/util'; diff --git a/packages/json-joy/src/json-crdt/model/api/NodeEvents.ts b/packages/json-joy/src/json-crdt/model/api/NodeEvents.ts index db19da0398..985c6a6b8c 100644 --- a/packages/json-joy/src/json-crdt/model/api/NodeEvents.ts +++ b/packages/json-joy/src/json-crdt/model/api/NodeEvents.ts @@ -1,7 +1,7 @@ import {MapFanOut, OnNewFanOut} from './fanout'; import type {FanOut, FanOutUnsubscribe} from 'thingies/lib/fanout'; import type {JsonNode, JsonNodeView} from '../../nodes'; -import type {SyncStore, SyncStoreUnsubscribe} from '../../../util/events/sync-store'; +import type {SyncStore, SyncStoreUnsubscribe} from 'thingies/lib/sync'; import type {NodeApi} from './nodes'; import type {ChangeEvent} from './events'; diff --git a/packages/json-joy/src/json-crdt/model/api/nodes.ts b/packages/json-joy/src/json-crdt/model/api/nodes.ts index 3c5104beb7..991cffcbf4 100644 --- a/packages/json-joy/src/json-crdt/model/api/nodes.ts +++ b/packages/json-joy/src/json-crdt/model/api/nodes.ts @@ -22,7 +22,7 @@ import type {Printable} from 'tree-dump/lib/types'; import type {ApiOperation, ApiPath, JsonNodeApi} from './types'; import type {VecNodeExtensionData} from '../../schema/types'; import type {Patch} from '../../../json-crdt-patch'; -import type {SyncStore} from '../../../util/events/sync-store'; +import type {SyncStore} from 'thingies/lib/sync'; import type {Model} from '../Model'; import type {JsonNode, JsonNodeView} from '../../nodes'; diff --git a/packages/json-joy/src/util/events/sync-store.ts b/packages/json-joy/src/util/events/sync-store.ts deleted file mode 100644 index d474cbdf55..0000000000 --- a/packages/json-joy/src/util/events/sync-store.ts +++ /dev/null @@ -1 +0,0 @@ -export * from 'thingies/lib/sync'; diff --git a/packages/peritext/package.json b/packages/peritext/package.json index 2b312e11ef..1c02329df2 100644 --- a/packages/peritext/package.json +++ b/packages/peritext/package.json @@ -44,7 +44,8 @@ "@jsonjoy.com/collaborative-ui": "workspace:*", "@jsonjoy.com/keyboard": "workspace:*", "json-joy": "workspace:*", - "mathlive": "^0.109.0" + "mathlive": "^0.109.0", + "thingies": "^2.6.0" }, "peerDependencies": { "react": "*", diff --git a/packages/peritext/src/editor/state/menus/CaretMenu.tsx b/packages/peritext/src/editor/state/menus/CaretMenu.tsx index 7386aa5cbf..12f06a8f1a 100644 --- a/packages/peritext/src/editor/state/menus/CaretMenu.tsx +++ b/packages/peritext/src/editor/state/menus/CaretMenu.tsx @@ -1,5 +1,5 @@ import * as React from 'react'; -// import {ValueSyncStore} from 'json-joy/lib/util/events/sync-store'; +// import {ValueSyncStore} from 'thingies/lib/sync'; import {secondBrain} from '../menus'; import {FontStyleButton} from '@jsonjoy.com/ui/lib/2-inline-block/FontStyleButton'; // import {type LeafBlock, type Peritext} from 'json-joy/lib/json-crdt-extensions'; diff --git a/packages/peritext/src/plugins/debug/RenderPeritext.tsx b/packages/peritext/src/plugins/debug/RenderPeritext.tsx index a123a6638e..3d5332aa1f 100644 --- a/packages/peritext/src/plugins/debug/RenderPeritext.tsx +++ b/packages/peritext/src/plugins/debug/RenderPeritext.tsx @@ -3,7 +3,7 @@ import {drule, rule, useTheme} from 'nano-theme'; import {context} from './context'; import {Button} from '../../web/components/Button'; import {Console} from './Console'; -import {Value} from 'json-joy/lib/util/events/sync-store'; +import {Value} from 'thingies/lib/sync'; import {useSyncStore} from '../../web/react/hooks'; import {DebugState} from './state'; import {CssClass} from '../../web/constants'; diff --git a/packages/peritext/src/plugins/debug/context.ts b/packages/peritext/src/plugins/debug/context.ts index 06a32b9608..4812c3b566 100644 --- a/packages/peritext/src/plugins/debug/context.ts +++ b/packages/peritext/src/plugins/debug/context.ts @@ -1,5 +1,5 @@ import * as React from 'react'; -import type {Value} from 'json-joy/lib/util/events/sync-store'; +import type {Value} from 'thingies/lib/sync'; import type {PeritextSurfaceState} from '../../web/state'; import type {DebugState} from './state'; diff --git a/packages/peritext/src/plugins/debug/state/index.tsx b/packages/peritext/src/plugins/debug/state/index.tsx index ebe4f3a916..20f0e71f36 100644 --- a/packages/peritext/src/plugins/debug/state/index.tsx +++ b/packages/peritext/src/plugins/debug/state/index.tsx @@ -1,4 +1,4 @@ -import {Value} from 'json-joy/lib/util/events/sync-store'; +import {Value} from 'thingies/lib/sync'; import type {UiLifeCycles} from '../../../web/types'; export class DebugState implements UiLifeCycles { diff --git a/packages/peritext/src/plugins/minimal/RenderPeritext.tsx b/packages/peritext/src/plugins/minimal/RenderPeritext.tsx index 46124e101a..ac799c7f89 100644 --- a/packages/peritext/src/plugins/minimal/RenderPeritext.tsx +++ b/packages/peritext/src/plugins/minimal/RenderPeritext.tsx @@ -1,7 +1,7 @@ import * as React from 'react'; import {Chrome} from './Chrome'; import {context, type MinimalPluginContextValue} from './context'; -import {Value} from 'json-joy/lib/util/events/sync-store'; +import {Value} from 'thingies/lib/sync'; import type {PeritextSurfaceState} from '../../web/state'; import type {ChangeDetail} from 'json-joy/lib/json-crdt-extensions/peritext/events'; diff --git a/packages/peritext/src/plugins/minimal/context.ts b/packages/peritext/src/plugins/minimal/context.ts index 99fa17e9b0..a20355699b 100644 --- a/packages/peritext/src/plugins/minimal/context.ts +++ b/packages/peritext/src/plugins/minimal/context.ts @@ -1,6 +1,6 @@ import * as React from 'react'; import type {PeritextSurfaceState} from '../../web/state'; -import type {Value} from 'json-joy/lib/util/events/sync-store'; +import type {Value} from 'thingies/lib/sync'; export interface MinimalPluginContextValue { ctx: PeritextSurfaceState; diff --git a/packages/peritext/src/web/react/hooks.ts b/packages/peritext/src/web/react/hooks.ts index e37379c8a8..3dc2247557 100644 --- a/packages/peritext/src/web/react/hooks.ts +++ b/packages/peritext/src/web/react/hooks.ts @@ -1,5 +1,5 @@ import * as React from 'react'; -import type {SyncStore} from 'json-joy/lib/util/events/sync-store'; +import type {SyncStore} from 'thingies/lib/sync'; export const useIsoLayoutEffect = typeof window === 'object' && window.document ? React.useLayoutEffect : React.useEffect; diff --git a/packages/peritext/src/web/state/index.ts b/packages/peritext/src/web/state/index.ts index 0d7bf06bb1..0ae347e601 100644 --- a/packages/peritext/src/web/state/index.ts +++ b/packages/peritext/src/web/state/index.ts @@ -1,6 +1,6 @@ import type {Log} from 'json-joy/lib/json-crdt/log/Log'; import {DomController} from '../dom/DomController'; -import {Value} from 'json-joy/lib/util/events/sync-store'; +import {Value} from 'thingies/lib/sync'; import {WebFacade} from '../dom/facade/WebFacade'; import type {PeritextHeadless} from 'json-joy/lib/json-crdt-extensions/peritext'; import type {PeritextPlugin} from '../react/types'; diff --git a/yarn.lock b/yarn.lock index 97ab7ea444..9516c7b3a9 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2081,6 +2081,7 @@ __metadata: json-joy: "workspace:*" react: "npm:^19.2.4" react-dom: "npm:^19.2.4" + thingies: "npm:^2.6.0" peerDependencies: react: ^19 tslib: "*" @@ -2690,6 +2691,7 @@ __metadata: "@jsonjoy.com/keyboard": "workspace:*" json-joy: "workspace:*" mathlive: "npm:^0.109.0" + thingies: "npm:^2.6.0" peerDependencies: react: "*" tslib: "*" From d8512f442a35b8486728912d7f417cf82d8873c0 Mon Sep 17 00:00:00 2001 From: streamich Date: Tue, 7 Jul 2026 14:53:27 +0200 Subject: [PATCH 11/14] =?UTF-8?q?refactor:=20=F0=9F=92=A1=20move=20event?= =?UTF-8?q?=20utils=20to=20util=20package?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../peritext/events/PeritextEventTarget.ts | 2 +- packages/peritext/package.json | 1 + packages/peritext/src/web/dom/controllers/InputController.ts | 2 +- packages/peritext/tsconfig.build.json | 3 +++ packages/peritext/tsconfig.json | 3 +++ packages/{json-joy/src/util => util/src}/events/Emitter.ts | 0 .../{json-joy/src/util => util/src}/events/TypedEventTarget.ts | 0 yarn.lock | 1 + 8 files changed, 10 insertions(+), 2 deletions(-) rename packages/{json-joy/src/util => util/src}/events/Emitter.ts (100%) rename packages/{json-joy/src/util => util/src}/events/TypedEventTarget.ts (100%) diff --git a/packages/json-joy/src/json-crdt-extensions/peritext/events/PeritextEventTarget.ts b/packages/json-joy/src/json-crdt-extensions/peritext/events/PeritextEventTarget.ts index 8b86fcf022..ef2d20bbd2 100644 --- a/packages/json-joy/src/json-crdt-extensions/peritext/events/PeritextEventTarget.ts +++ b/packages/json-joy/src/json-crdt-extensions/peritext/events/PeritextEventTarget.ts @@ -1,4 +1,4 @@ -import {SubscriptionEventTarget} from '../../../util/events/TypedEventTarget'; +import {SubscriptionEventTarget} from '@jsonjoy.com/util/lib/events/TypedEventTarget'; import type { PeritextEventDetailMap, CursorDetail, diff --git a/packages/peritext/package.json b/packages/peritext/package.json index 1c02329df2..a9d8a3676d 100644 --- a/packages/peritext/package.json +++ b/packages/peritext/package.json @@ -43,6 +43,7 @@ "@jsonjoy.com/collaborative-react": "workspace:*", "@jsonjoy.com/collaborative-ui": "workspace:*", "@jsonjoy.com/keyboard": "workspace:*", + "@jsonjoy.com/util": "workspace:*", "json-joy": "workspace:*", "mathlive": "^0.109.0", "thingies": "^2.6.0" diff --git a/packages/peritext/src/web/dom/controllers/InputController.ts b/packages/peritext/src/web/dom/controllers/InputController.ts index 54f8522a0e..f008438fda 100644 --- a/packages/peritext/src/web/dom/controllers/InputController.ts +++ b/packages/peritext/src/web/dom/controllers/InputController.ts @@ -2,7 +2,7 @@ import {unit} from '../../util'; import {SliceTypeName} from 'json-joy/lib/json-crdt-extensions/peritext/slice/constants'; import type {Peritext} from 'json-joy/lib/json-crdt-extensions/peritext'; import type {PeritextEventTarget} from 'json-joy/lib/json-crdt-extensions/peritext/events/PeritextEventTarget'; -import type {TypedEventTarget} from 'json-joy/lib/util/events/TypedEventTarget'; +import type {TypedEventTarget} from '@jsonjoy.com/util/lib/events/TypedEventTarget'; import type {UiLifeCycles} from '../../types'; import type {DomController} from './../DomController'; diff --git a/packages/peritext/tsconfig.build.json b/packages/peritext/tsconfig.build.json index 91e1ae0d9c..23bc3258e3 100644 --- a/packages/peritext/tsconfig.build.json +++ b/packages/peritext/tsconfig.build.json @@ -34,6 +34,9 @@ }, { "path": "../json-joy/tsconfig.build.json" + }, + { + "path": "../util/tsconfig.build.json" } ] } diff --git a/packages/peritext/tsconfig.json b/packages/peritext/tsconfig.json index 4dbde50066..81e87fd0b4 100644 --- a/packages/peritext/tsconfig.json +++ b/packages/peritext/tsconfig.json @@ -35,6 +35,9 @@ }, { "path": "../keyboard" + }, + { + "path": "../util" } ] } diff --git a/packages/json-joy/src/util/events/Emitter.ts b/packages/util/src/events/Emitter.ts similarity index 100% rename from packages/json-joy/src/util/events/Emitter.ts rename to packages/util/src/events/Emitter.ts diff --git a/packages/json-joy/src/util/events/TypedEventTarget.ts b/packages/util/src/events/TypedEventTarget.ts similarity index 100% rename from packages/json-joy/src/util/events/TypedEventTarget.ts rename to packages/util/src/events/TypedEventTarget.ts diff --git a/yarn.lock b/yarn.lock index 9516c7b3a9..ebeb0fcb49 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2689,6 +2689,7 @@ __metadata: "@jsonjoy.com/collaborative-react": "workspace:*" "@jsonjoy.com/collaborative-ui": "workspace:*" "@jsonjoy.com/keyboard": "workspace:*" + "@jsonjoy.com/util": "workspace:*" json-joy: "workspace:*" mathlive: "npm:^0.109.0" thingies: "npm:^2.6.0" From 0a50253ff43b85a5f96846c546fd002be8152f66 Mon Sep 17 00:00:00 2001 From: streamich Date: Tue, 7 Jul 2026 15:01:22 +0200 Subject: [PATCH 12/14] =?UTF-8?q?refactor:=20=F0=9F=92=A1=20move=20`saveSe?= =?UTF-8?q?lection`?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/json-crdt-extensions/peritext/annals/WebUndo.ts | 2 +- .../peritext/events/clipboard/PeritextClipboardImpl.ts | 2 +- .../src/{ => json-crdt-extensions/peritext}/util/dom.ts | 0 3 files changed, 2 insertions(+), 2 deletions(-) rename packages/json-joy/src/{ => json-crdt-extensions/peritext}/util/dom.ts (100%) diff --git a/packages/json-joy/src/json-crdt-extensions/peritext/annals/WebUndo.ts b/packages/json-joy/src/json-crdt-extensions/peritext/annals/WebUndo.ts index e5f32521e2..dae1ad4f52 100644 --- a/packages/json-joy/src/json-crdt-extensions/peritext/annals/WebUndo.ts +++ b/packages/json-joy/src/json-crdt-extensions/peritext/annals/WebUndo.ts @@ -1,4 +1,4 @@ -import {saveSelection} from '../../../util/dom'; +import {saveSelection} from '../util/dom'; import type {UndoManager, UndoItem} from './types'; import type {UiLifeCycles} from '../types'; diff --git a/packages/json-joy/src/json-crdt-extensions/peritext/events/clipboard/PeritextClipboardImpl.ts b/packages/json-joy/src/json-crdt-extensions/peritext/events/clipboard/PeritextClipboardImpl.ts index 3af9bee138..827f6c735c 100644 --- a/packages/json-joy/src/json-crdt-extensions/peritext/events/clipboard/PeritextClipboardImpl.ts +++ b/packages/json-joy/src/json-crdt-extensions/peritext/events/clipboard/PeritextClipboardImpl.ts @@ -1,4 +1,4 @@ -import {saveSelection} from '../../../../util/dom'; +import {saveSelection} from '../../util/dom'; import {MemPlatformClipboard} from './MemPlatformClipboard'; import type {PeritextClipboard, PeritextClipboardData, PlatformClipboard} from './types'; diff --git a/packages/json-joy/src/util/dom.ts b/packages/json-joy/src/json-crdt-extensions/peritext/util/dom.ts similarity index 100% rename from packages/json-joy/src/util/dom.ts rename to packages/json-joy/src/json-crdt-extensions/peritext/util/dom.ts From 125f0f06b28b44a2ed87d90a6ef5943508a756f3 Mon Sep 17 00:00:00 2001 From: streamich Date: Tue, 7 Jul 2026 15:46:09 +0200 Subject: [PATCH 13/14] =?UTF-8?q?feat:=20=F0=9F=8E=B8=20create=20`diff`=20?= =?UTF-8?q?package?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/collaborative-slate/package.json | 1 + .../src/sync/applyPatch.ts | 2 +- .../collaborative-slate/tsconfig.build.json | 3 + packages/collaborative-slate/tsconfig.json | 3 + packages/collaborative-str/package.json | 1 + packages/collaborative-str/src/StrBinding.ts | 2 +- .../collaborative-str/tsconfig.build.json | 3 + packages/collaborative-str/tsconfig.json | 3 + packages/diff/LICENSE | 201 +++++++++++++++++ packages/diff/README.md | 24 +++ packages/diff/SECURITY.md | 13 ++ packages/diff/package.json | 78 +++++++ .../src}/__tests__/bin-fuzz.spec.ts | 0 .../diff => diff/src}/__tests__/bin.spec.ts | 0 .../src}/__tests__/line-fuzzer.spec.ts | 0 .../diff => diff/src}/__tests__/line.spec.ts | 0 .../util/diff => diff/src}/__tests__/line.ts | 0 .../src}/__tests__/str-fuzz.spec.ts | 0 .../diff => diff/src}/__tests__/str.spec.ts | 0 .../util/diff => diff/src}/__tests__/util.ts | 0 .../src/util/diff => diff/src}/bin.ts | 0 packages/diff/src/index.ts | 3 + .../src/util/diff => diff/src}/line.ts | 0 .../src/util/diff => diff/src}/str.ts | 0 packages/diff/tsconfig.build.json | 25 +++ packages/diff/tsconfig.json | 26 +++ packages/json-joy/package.json | 1 + .../src/json-crdt-diff/JsonCrdtDiff.ts | 6 +- .../src/json-patch-diff/JsonPatchDiff.ts | 4 +- packages/json-joy/src/util/diff/str-utils.ts | 204 ------------------ packages/json-joy/tsconfig.build.json | 3 + packages/json-joy/tsconfig.json | 3 + packages/peritext/package.json | 1 + .../inline/components/FmtManagePane/state.ts | 2 +- packages/peritext/tsconfig.build.json | 3 + packages/peritext/tsconfig.json | 3 + tsconfig.solution.json | 1 + yarn.lock | 16 ++ 38 files changed, 423 insertions(+), 212 deletions(-) create mode 100644 packages/diff/LICENSE create mode 100644 packages/diff/README.md create mode 100644 packages/diff/SECURITY.md create mode 100644 packages/diff/package.json rename packages/{json-joy/src/util/diff => diff/src}/__tests__/bin-fuzz.spec.ts (100%) rename packages/{json-joy/src/util/diff => diff/src}/__tests__/bin.spec.ts (100%) rename packages/{json-joy/src/util/diff => diff/src}/__tests__/line-fuzzer.spec.ts (100%) rename packages/{json-joy/src/util/diff => diff/src}/__tests__/line.spec.ts (100%) rename packages/{json-joy/src/util/diff => diff/src}/__tests__/line.ts (100%) rename packages/{json-joy/src/util/diff => diff/src}/__tests__/str-fuzz.spec.ts (100%) rename packages/{json-joy/src/util/diff => diff/src}/__tests__/str.spec.ts (100%) rename packages/{json-joy/src/util/diff => diff/src}/__tests__/util.ts (100%) rename packages/{json-joy/src/util/diff => diff/src}/bin.ts (100%) create mode 100644 packages/diff/src/index.ts rename packages/{json-joy/src/util/diff => diff/src}/line.ts (100%) rename packages/{json-joy/src/util/diff => diff/src}/str.ts (100%) create mode 100644 packages/diff/tsconfig.build.json create mode 100644 packages/diff/tsconfig.json delete mode 100644 packages/json-joy/src/util/diff/str-utils.ts diff --git a/packages/collaborative-slate/package.json b/packages/collaborative-slate/package.json index d249bc4b06..dc21a03386 100644 --- a/packages/collaborative-slate/package.json +++ b/packages/collaborative-slate/package.json @@ -82,6 +82,7 @@ "dependencies": { "@jsonjoy.com/collaborative-peritext": "workspace:*", "@jsonjoy.com/collaborative-presence": "workspace:*", + "@jsonjoy.com/diff": "workspace:*", "@jsonjoy.com/json-equal": "workspace:*", "@jsonjoy.com/ui": "workspace:*", "code-colors": "^2.4.0", diff --git a/packages/collaborative-slate/src/sync/applyPatch.ts b/packages/collaborative-slate/src/sync/applyPatch.ts index 81522b1141..bb06da548b 100644 --- a/packages/collaborative-slate/src/sync/applyPatch.ts +++ b/packages/collaborative-slate/src/sync/applyPatch.ts @@ -5,7 +5,7 @@ */ import {Transforms, Editor} from 'slate'; -import * as str from 'json-joy/lib/util/diff/str'; +import * as str from '@jsonjoy.com/diff/lib/str'; import {deepEqual} from '@jsonjoy.com/json-equal'; import type {SlateDescendantNode, SlateDocument, SlateElementNode, SlateTextNode} from '../types'; diff --git a/packages/collaborative-slate/tsconfig.build.json b/packages/collaborative-slate/tsconfig.build.json index 5843ebca23..2eb59d2800 100644 --- a/packages/collaborative-slate/tsconfig.build.json +++ b/packages/collaborative-slate/tsconfig.build.json @@ -29,6 +29,9 @@ { "path": "../collaborative-presence/tsconfig.build.json" }, + { + "path": "../diff/tsconfig.build.json" + }, { "path": "../json-equal/tsconfig.build.json" }, diff --git a/packages/collaborative-slate/tsconfig.json b/packages/collaborative-slate/tsconfig.json index 1dd874246a..55899802d3 100644 --- a/packages/collaborative-slate/tsconfig.json +++ b/packages/collaborative-slate/tsconfig.json @@ -30,6 +30,9 @@ { "path": "../collaborative-presence" }, + { + "path": "../diff" + }, { "path": "../json-equal" }, diff --git a/packages/collaborative-str/package.json b/packages/collaborative-str/package.json index abb9e52c76..009f4c61c6 100644 --- a/packages/collaborative-str/package.json +++ b/packages/collaborative-str/package.json @@ -35,6 +35,7 @@ "crdt" ], "dependencies": { + "@jsonjoy.com/diff": "workspace:*", "json-joy": "workspace:*" }, "peerDependencies": { diff --git a/packages/collaborative-str/src/StrBinding.ts b/packages/collaborative-str/src/StrBinding.ts index cebe335e6b..7b4e79e0ee 100644 --- a/packages/collaborative-str/src/StrBinding.ts +++ b/packages/collaborative-str/src/StrBinding.ts @@ -1,7 +1,7 @@ import {invokeFirstOnly} from './util'; import {Selection} from './Selection'; import {applyChange} from './util'; -import {diff, diffEdit} from 'json-joy/lib/util/diff/str'; +import {diff, diffEdit} from '@jsonjoy.com/diff/lib/str'; import type {CollaborativeStr, EditorFacade, SimpleChange} from './types'; const enum PATCH_OP_TYPE { diff --git a/packages/collaborative-str/tsconfig.build.json b/packages/collaborative-str/tsconfig.build.json index bc920f514b..b2a380cdad 100644 --- a/packages/collaborative-str/tsconfig.build.json +++ b/packages/collaborative-str/tsconfig.build.json @@ -23,6 +23,9 @@ "src/**/*.stories.tsx" ], "references": [ + { + "path": "../diff/tsconfig.build.json" + }, { "path": "../json-joy/tsconfig.build.json" } diff --git a/packages/collaborative-str/tsconfig.json b/packages/collaborative-str/tsconfig.json index 219df2258a..c96de9874d 100644 --- a/packages/collaborative-str/tsconfig.json +++ b/packages/collaborative-str/tsconfig.json @@ -24,6 +24,9 @@ "src/**/*.stories.tsx" ], "references": [ + { + "path": "../diff" + }, { "path": "../json-joy" } diff --git a/packages/diff/LICENSE b/packages/diff/LICENSE new file mode 100644 index 0000000000..75635b39a3 --- /dev/null +++ b/packages/diff/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2023 Vadims @streamich Daleckis + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/packages/diff/README.md b/packages/diff/README.md new file mode 100644 index 0000000000..7f37f597c0 --- /dev/null +++ b/packages/diff/README.md @@ -0,0 +1,24 @@ +# `@jsonjoy.com/diff` + +Fast diff algorithms for strings, lines, and binary data. Zero dependencies. + +- `str` — character-level string diffing (Myers-style, with common + prefix/suffix and overlap optimizations), patch normalization, inversion, + and caret-aware `diffEdit` for text inputs. +- `line` — line-level diffing built on top of `str`, with per-line patch aggregation. +- `bin` — `Uint8Array` diffing via a binary-to-string mapping over `str`. + +```ts +import {str} from '@jsonjoy.com/diff'; + +const patch = str.diff('hello world', 'hello there world'); +str.apply(patch, src.length, /* ... */); +str.src(patch); // 'hello world' +str.dst(patch); // 'hello there world' +``` + +Or deep-import a single module: + +```ts +import * as str from '@jsonjoy.com/diff/lib/str'; +``` diff --git a/packages/diff/SECURITY.md b/packages/diff/SECURITY.md new file mode 100644 index 0000000000..a5497b62af --- /dev/null +++ b/packages/diff/SECURITY.md @@ -0,0 +1,13 @@ +# Security Policy + +## Supported Versions + +We release patches for security vulnerabilities. The latest major version +will support security patches. + +## Reporting a Vulnerability + +Please report (suspected) security vulnerabilities to +**[streamich@gmail.com](mailto:streamich@gmail.com)**. We will try to respond +within 48 hours. If the issue is confirmed, we will release a patch as soon +as possible depending on complexity. diff --git a/packages/diff/package.json b/packages/diff/package.json new file mode 100644 index 0000000000..83ef777cde --- /dev/null +++ b/packages/diff/package.json @@ -0,0 +1,78 @@ +{ + "name": "@jsonjoy.com/diff", + "publishConfig": { + "access": "public" + }, + "version": "18.28.0", + "description": "Fast diff algorithms for strings, lines, and binary data", + "author": { + "name": "streamich", + "url": "https://github.com/streamich" + }, + "homepage": "https://github.com/streamich/json-joy/tree/master/packages/diff", + "repository": { + "type": "git", + "url": "https://github.com/streamich/json-joy.git", + "directory": "packages/diff" + }, + "license": "Apache-2.0", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/streamich" + }, + "keywords": [ + "diff", + "patch", + "text-diff", + "string-diff", + "binary-diff", + "line-diff", + "myers", + "diff-match-patch" + ], + "peerDependencies": { + "tslib": "*" + }, + "devDependencies": { + "@jsonjoy.com/buffers": "workspace:*", + "@jsonjoy.com/json-random": "workspace:*", + "@jsonjoy.com/util": "workspace:*" + }, + "engines": { + "node": ">=10.0" + }, + "main": "lib/index.js", + "types": "lib/index.d.ts", + "typings": "lib/index.d.ts", + "files": [ + "LICENSE", + "lib/" + ], + "scripts": { + "clean": "npx rimraf lib typedocs coverage gh-pages yarn-error.log", + "build": "tsc -b tsconfig.build.json", + "typedoc": "typedoc", + "typecheck": "tsc -b --noEmit" + }, + "jest": { + "preset": "ts-jest", + "testEnvironment": "node", + "moduleFileExtensions": [ + "ts", + "js", + "tsx" + ], + "transform": { + "^.+\\.tsx?$": "ts-jest" + }, + "transformIgnorePatterns": [ + ".*/node_modules/.*" + ], + "testRegex": ".*/(__tests__|__jest__|demo)/.*(? { - let changes = false; - const equalities = []; // Stack of indices where equalities are found. - let equalitiesLength = 0; // Keeping our own length var is faster in JS. - /** @type {?string} */ - let lastequality = null; - // Always equal to diffs[equalities[equalitiesLength - 1]][1] - let pointer = 0; // Index of current position. - // Number of characters that changed prior to the equality. - let length_insertions1 = 0; - let length_deletions1 = 0; - // Number of characters that changed after the equality. - let length_insertions2 = 0; - let length_deletions2 = 0; - while (pointer < patch.length) { - if (patch[pointer][0] === PATCH_OP_TYPE.EQL) { - // Equality found. - equalities[equalitiesLength++] = pointer; - length_insertions1 = length_insertions2; - length_deletions1 = length_deletions2; - length_insertions2 = 0; - length_deletions2 = 0; - lastequality = patch[pointer][1]; - } else { - // An insertion or deletion. - if (patch[pointer][0] === PATCH_OP_TYPE.INS) { - length_insertions2 += patch[pointer][1].length; - } else { - length_deletions2 += patch[pointer][1].length; - } - // Eliminate an equality that is smaller or equal to the edits on both - // sides of it. - if ( - lastequality && - lastequality.length <= Math.max(length_insertions1, length_deletions1) && - lastequality.length <= Math.max(length_insertions2, length_deletions2) - ) { - // Duplicate record. - patch.splice(equalities[equalitiesLength - 1], 0, [PATCH_OP_TYPE.DEL, lastequality]); - // Change second copy to insert. - patch[equalities[equalitiesLength - 1] + 1][0] = PATCH_OP_TYPE.INS; - // Throw away the equality we just deleted. - equalitiesLength--; - // Throw away the previous equality (it needs to be reevaluated). - equalitiesLength--; - pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1; - length_insertions1 = 0; // Reset the counters. - length_deletions1 = 0; - length_insertions2 = 0; - length_deletions2 = 0; - lastequality = null; - changes = true; - } - } - pointer++; - } - - // Normalize the diff. - if (changes) { - cleanupPatch(patch); - } - cleanupSemanticLossless(patch); - - // Find any overlaps between deletions and insertions. - // e.g: abcxxxxxxdef - // -> abcxxxdef - // e.g: xxxabcdefxxx - // -> defxxxabc - // Only extract an overlap if it is as big as the edit ahead or behind it. - pointer = 1; - while (pointer < patch.length) { - if (patch[pointer - 1][0] === PATCH_OP_TYPE.DEL && patch[pointer][0] === PATCH_OP_TYPE.INS) { - const deletion = patch[pointer - 1][1]; - const insertion = patch[pointer][1]; - const overlap_length1 = overlap(deletion, insertion); - const overlap_length2 = overlap(insertion, deletion); - if (overlap_length1 >= overlap_length2) { - if (overlap_length1 >= deletion.length / 2 || overlap_length1 >= insertion.length / 2) { - // Overlap found. Insert an equality and trim the surrounding edits. - patch.splice(pointer, 0, [PATCH_OP_TYPE.EQL, insertion.substring(0, overlap_length1)]); - patch[pointer - 1][1] = deletion.substring(0, deletion.length - overlap_length1); - patch[pointer + 1][1] = insertion.substring(overlap_length1); - pointer++; - } - } else { - if (overlap_length2 >= deletion.length / 2 || overlap_length2 >= insertion.length / 2) { - // Reverse overlap found. - // Insert an equality and swap and trim the surrounding edits. - patch.splice(pointer, 0, [PATCH_OP_TYPE.EQL, deletion.substring(0, overlap_length2)]); - patch[pointer - 1][0] = PATCH_OP_TYPE.INS; - patch[pointer - 1][1] = insertion.substring(0, insertion.length - overlap_length2); - patch[pointer + 1][0] = PATCH_OP_TYPE.DEL; - patch[pointer + 1][1] = deletion.substring(overlap_length2); - pointer++; - } - } - pointer++; - } - pointer++; - } -}; - -const nonAlphaNumericRegex_ = /[^a-zA-Z0-9]/; -const whitespaceRegex_ = /\s/; -const linebreakRegex_ = /[\r\n]/; -const blanklineEndRegex_ = /\n\r?\n$/; -const blanklineStartRegex_ = /^\r?\n\r?\n/; - -/** - * Given two strings, compute a score representing whether the internal - * boundary falls on logical boundaries. - * Scores range from 6 (best) to 0 (worst). - * Closure, but does not reference any external variables. - * @param {string} one First string. - * @param {string} two Second string. - * @return {number} The score. - * @private - */ -const semanticScore = (one: string, two: string) => { - if (!one || !two) return 6; - const char1 = one.charAt(one.length - 1); - const char2 = two.charAt(0); - const nonAlphaNumeric1 = char1.match(nonAlphaNumericRegex_); - const nonAlphaNumeric2 = char2.match(nonAlphaNumericRegex_); - const whitespace1 = nonAlphaNumeric1 && char1.match(whitespaceRegex_); - const whitespace2 = nonAlphaNumeric2 && char2.match(whitespaceRegex_); - const lineBreak1 = whitespace1 && char1.match(linebreakRegex_); - const lineBreak2 = whitespace2 && char2.match(linebreakRegex_); - const blankLine1 = lineBreak1 && one.match(blanklineEndRegex_); - const blankLine2 = lineBreak2 && two.match(blanklineStartRegex_); - if (blankLine1 || blankLine2) return 5; - else if (lineBreak1 || lineBreak2) return 4; - else if (nonAlphaNumeric1 && !whitespace1 && whitespace2) return 3; - else if (whitespace1 || whitespace2) return 2; - else if (nonAlphaNumeric1 || nonAlphaNumeric2) return 1; - return 0; -}; - -/** - * Look for single edits surrounded on both sides by equalities - * which can be shifted sideways to align the edit to a word boundary. - * e.g: The cat came. -> The cat came. - * @param {!Array.} patch Array of diff tuples. - */ -const cleanupSemanticLossless = (patch: Patch): void => { - let pointer = 1; - // Intentionally ignore the first and last element (don't need checking). - while (pointer < patch.length - 1) { - if (patch[pointer - 1][0] === PATCH_OP_TYPE.EQL && patch[pointer + 1][0] === PATCH_OP_TYPE.EQL) { - // This is a single edit surrounded by equalities. - let equality1 = patch[pointer - 1][1]; - let edit = patch[pointer][1]; - let equality2 = patch[pointer + 1][1]; - - // First, shift the edit as far left as possible. - const commonOffset = sfx(equality1, edit); - if (commonOffset) { - const commonString = edit.substring(edit.length - commonOffset); - equality1 = equality1.substring(0, equality1.length - commonOffset); - edit = commonString + edit.substring(0, edit.length - commonOffset); - equality2 = commonString + equality2; - } - - // Second, step character by character right, looking for the best fit. - let bestEquality1 = equality1; - let bestEdit = edit; - let bestEquality2 = equality2; - let bestScore = semanticScore(equality1, edit) + semanticScore(edit, equality2); - while (edit.charAt(0) === equality2.charAt(0)) { - equality1 += edit.charAt(0); - edit = edit.substring(1) + equality2.charAt(0); - equality2 = equality2.substring(1); - const score = semanticScore(equality1, edit) + semanticScore(edit, equality2); - // The >= encourages trailing rather than leading whitespace on edits. - if (score >= bestScore) { - bestScore = score; - bestEquality1 = equality1; - bestEdit = edit; - bestEquality2 = equality2; - } - } - - if (patch[pointer - 1][1] !== bestEquality1) { - // We have an improvement, save it back to the diff. - if (bestEquality1) { - patch[pointer - 1][1] = bestEquality1; - } else { - patch.splice(pointer - 1, 1); - pointer--; - } - patch[pointer][1] = bestEdit; - if (bestEquality2) { - patch[pointer + 1][1] = bestEquality2; - } else { - patch.splice(pointer + 1, 1); - pointer--; - } - } - } - pointer++; - } -}; diff --git a/packages/json-joy/tsconfig.build.json b/packages/json-joy/tsconfig.build.json index 1974798fc8..ef998b8a40 100644 --- a/packages/json-joy/tsconfig.build.json +++ b/packages/json-joy/tsconfig.build.json @@ -29,6 +29,9 @@ { "path": "../buffers/tsconfig.build.json" }, + { + "path": "../diff/tsconfig.build.json" + }, { "path": "../json-expression/tsconfig.build.json" }, diff --git a/packages/json-joy/tsconfig.json b/packages/json-joy/tsconfig.json index 1cb6955a0e..f6e4536c7d 100644 --- a/packages/json-joy/tsconfig.json +++ b/packages/json-joy/tsconfig.json @@ -14,6 +14,9 @@ { "path": "../buffers" }, + { + "path": "../diff" + }, { "path": "../json-expression" }, diff --git a/packages/peritext/package.json b/packages/peritext/package.json index a9d8a3676d..4c9d4841ed 100644 --- a/packages/peritext/package.json +++ b/packages/peritext/package.json @@ -42,6 +42,7 @@ "@cortex-js/compute-engine": "^0.55.6", "@jsonjoy.com/collaborative-react": "workspace:*", "@jsonjoy.com/collaborative-ui": "workspace:*", + "@jsonjoy.com/diff": "workspace:*", "@jsonjoy.com/keyboard": "workspace:*", "@jsonjoy.com/util": "workspace:*", "json-joy": "workspace:*", diff --git a/packages/peritext/src/editor/inline/components/FmtManagePane/state.ts b/packages/peritext/src/editor/inline/components/FmtManagePane/state.ts index d35a36d1b4..4e9df50d0b 100644 --- a/packages/peritext/src/editor/inline/components/FmtManagePane/state.ts +++ b/packages/peritext/src/editor/inline/components/FmtManagePane/state.ts @@ -2,7 +2,7 @@ import {SavedFmt} from '../../../state/formattings'; import {SynthFmt} from '../../../state/formattings/SynthFmt'; import {Slice} from 'json-joy/lib/json-crdt-extensions/peritext/slice/Slice'; import {JsonCrdtDiff} from 'json-joy/lib/json-crdt-diff/JsonCrdtDiff'; -import * as str from 'json-joy/lib/util/diff/str'; +import * as str from '@jsonjoy.com/diff/lib/str'; import * as sync from 'thingies/lib/sync'; import type {Inline} from 'json-joy/lib/json-crdt-extensions'; import type {EditorState} from '../../../state'; diff --git a/packages/peritext/tsconfig.build.json b/packages/peritext/tsconfig.build.json index 23bc3258e3..f7f9d66daa 100644 --- a/packages/peritext/tsconfig.build.json +++ b/packages/peritext/tsconfig.build.json @@ -23,6 +23,9 @@ "src/**/*.stories.tsx" ], "references": [ + { + "path": "../diff/tsconfig.build.json" + }, { "path": "../collaborative-react/tsconfig.build.json" }, diff --git a/packages/peritext/tsconfig.json b/packages/peritext/tsconfig.json index 81e87fd0b4..95b67c8618 100644 --- a/packages/peritext/tsconfig.json +++ b/packages/peritext/tsconfig.json @@ -24,6 +24,9 @@ "src/**/*.stories.tsx" ], "references": [ + { + "path": "../diff" + }, { "path": "../collaborative-react" }, diff --git a/tsconfig.solution.json b/tsconfig.solution.json index a7ac56ec98..371e4050f9 100644 --- a/tsconfig.solution.json +++ b/tsconfig.solution.json @@ -6,6 +6,7 @@ { "path": "packages/codegen/tsconfig.build.json" }, { "path": "packages/channel/tsconfig.build.json" }, { "path": "packages/json-equal/tsconfig.build.json" }, + { "path": "packages/diff/tsconfig.build.json" }, { "path": "packages/json-hash/tsconfig.build.json" }, { "path": "packages/json-random/tsconfig.build.json" }, { "path": "packages/json-path/tsconfig.build.json" }, diff --git a/yarn.lock b/yarn.lock index ebeb0fcb49..1be232baee 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2095,6 +2095,7 @@ __metadata: "@jsonjoy.com/collaborative-peritext": "workspace:*" "@jsonjoy.com/collaborative-presence": "workspace:*" "@jsonjoy.com/collaborative-ui": "workspace:*" + "@jsonjoy.com/diff": "workspace:*" "@jsonjoy.com/json-equal": "workspace:*" "@jsonjoy.com/ui": "workspace:*" "@types/react": "npm:^19" @@ -2132,6 +2133,7 @@ __metadata: version: 0.0.0-use.local resolution: "@jsonjoy.com/collaborative-str@workspace:packages/collaborative-str" dependencies: + "@jsonjoy.com/diff": "workspace:*" "@types/react": "npm:^19" "@types/react-dom": "npm:^19" json-joy: "workspace:*" @@ -2203,6 +2205,18 @@ __metadata: languageName: unknown linkType: soft +"@jsonjoy.com/diff@workspace:*, @jsonjoy.com/diff@workspace:packages/diff": + version: 0.0.0-use.local + resolution: "@jsonjoy.com/diff@workspace:packages/diff" + dependencies: + "@jsonjoy.com/buffers": "workspace:*" + "@jsonjoy.com/json-random": "workspace:*" + "@jsonjoy.com/util": "workspace:*" + peerDependencies: + tslib: "*" + languageName: unknown + linkType: soft + "@jsonjoy.com/fs-core@npm:4.56.10": version: 4.56.10 resolution: "@jsonjoy.com/fs-core@npm:4.56.10" @@ -2688,6 +2702,7 @@ __metadata: "@cortex-js/compute-engine": "npm:^0.55.6" "@jsonjoy.com/collaborative-react": "workspace:*" "@jsonjoy.com/collaborative-ui": "workspace:*" + "@jsonjoy.com/diff": "workspace:*" "@jsonjoy.com/keyboard": "workspace:*" "@jsonjoy.com/util": "workspace:*" json-joy: "workspace:*" @@ -10108,6 +10123,7 @@ __metadata: dependencies: "@jsonjoy.com/base64": "workspace:*" "@jsonjoy.com/buffers": "workspace:*" + "@jsonjoy.com/diff": "workspace:*" "@jsonjoy.com/json-equal": "workspace:*" "@jsonjoy.com/json-expression": "workspace:*" "@jsonjoy.com/json-hash": "workspace:*" From 94b2c1962bbf11c1a8aa72d466c33148b3fe7666 Mon Sep 17 00:00:00 2001 From: streamich Date: Tue, 7 Jul 2026 16:10:58 +0200 Subject: [PATCH 14/14] =?UTF-8?q?chore:=20=F0=9F=A4=96=20improve=20setup?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/diff/README.md | 5 +++-- packages/diff/package.json | 3 ++- packages/json-joy/package.json | 1 - yarn.lock | 2 +- 4 files changed, 6 insertions(+), 5 deletions(-) diff --git a/packages/diff/README.md b/packages/diff/README.md index 7f37f597c0..e8021267e1 100644 --- a/packages/diff/README.md +++ b/packages/diff/README.md @@ -11,8 +11,9 @@ Fast diff algorithms for strings, lines, and binary data. Zero dependencies. ```ts import {str} from '@jsonjoy.com/diff'; -const patch = str.diff('hello world', 'hello there world'); -str.apply(patch, src.length, /* ... */); +const src = 'hello world'; +const patch = str.diff(src, 'hello there world'); +str.apply(patch, src.length, onInsert, onDelete); str.src(patch); // 'hello world' str.dst(patch); // 'hello there world' ``` diff --git a/packages/diff/package.json b/packages/diff/package.json index 83ef777cde..a277282ead 100644 --- a/packages/diff/package.json +++ b/packages/diff/package.json @@ -36,7 +36,8 @@ "devDependencies": { "@jsonjoy.com/buffers": "workspace:*", "@jsonjoy.com/json-random": "workspace:*", - "@jsonjoy.com/util": "workspace:*" + "@jsonjoy.com/util": "workspace:*", + "fast-diff": "^1.3.0" }, "engines": { "node": ">=10.0" diff --git a/packages/json-joy/package.json b/packages/json-joy/package.json index 44a1ec7bcf..2881f015e6 100644 --- a/packages/json-joy/package.json +++ b/packages/json-joy/package.json @@ -106,7 +106,6 @@ "collaborative-input": "^1.7.0", "collaborative-ui": "^1.7.1", "editing-traces": "https://github.com/streamich/editing-traces#71c6d732956dbe08a490f8cd9764214bd3d4c9b7", - "fast-diff": "^1.3.0", "fast-json-patch": "^3.1.1", "html-webpack-plugin": "^5.6.0", "jest": "^30.2.0", diff --git a/yarn.lock b/yarn.lock index 1be232baee..1e3d379238 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2212,6 +2212,7 @@ __metadata: "@jsonjoy.com/buffers": "workspace:*" "@jsonjoy.com/json-random": "workspace:*" "@jsonjoy.com/util": "workspace:*" + fast-diff: "npm:^1.3.0" peerDependencies: tslib: "*" languageName: unknown @@ -10143,7 +10144,6 @@ __metadata: collaborative-input: "npm:^1.7.0" collaborative-ui: "npm:^1.7.1" editing-traces: "https://github.com/streamich/editing-traces#71c6d732956dbe08a490f8cd9764214bd3d4c9b7" - fast-diff: "npm:^1.3.0" fast-json-patch: "npm:^3.1.1" html-webpack-plugin: "npm:^5.6.0" hyperdyperid: "npm:^1.2.0"