@tenonhq/dovetail-core 0.0.132 → 0.0.134

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,193 @@
1
+ "use strict";
2
+ /**
3
+ * Record folder naming: the one place a record's on-disk folder name is decided.
4
+ *
5
+ * The rule, for the records of ONE table in ONE application:
6
+ *
7
+ * 1. A record is named after its display name.
8
+ * 2. When another record's name is the same ignoring letter case and Unicode
9
+ * normalization form, every record of that group gets
10
+ * ` (first 8 characters of its sys_id)` added.
11
+ * 3. When two records of a group also share those 8 characters, each of them
12
+ * gets ` (its full sys_id)` instead. Only the records that collide are
13
+ * lengthened; their other namesakes keep 8 characters.
14
+ * 4. A name no disk can hold (see isSafeFolderName) falls back to the sys_id.
15
+ *
16
+ * Why case and normalization count: macOS and Windows compare folder names
17
+ * without regard to letter case (macOS also without regard to normalization
18
+ * form), Linux compares bytes. Deciding collisions with the strictest of the
19
+ * three gives the same tree on all of them.
20
+ *
21
+ * Why step 3 jumps straight to the full id rather than growing a few characters
22
+ * at a time: sys_ids generated in one transaction (the access controls of a new
23
+ * table) are identical in all but their last two or three characters, so a
24
+ * stepwise suffix ends at 30+ characters anyway, and its length would depend on
25
+ * which other ids happen to exist. Add a third twin later and the first two
26
+ * would be renamed again. The full id is the only length that is unique by
27
+ * construction, so a record's name depends on one yes-or-no fact (does a
28
+ * namesake share my first 8 characters) and never on how much of the id that
29
+ * namesake happens to share.
30
+ *
31
+ * Why every colliding record is renamed and none keeps the short name: the
32
+ * record that kept `Name (first 8)` would hand that folder to its twin the day
33
+ * it is deleted, and a push from that folder would then write the wrong record.
34
+ *
35
+ * The instance names records by steps 1 to 3 as well (DovetailUtilsMS). This
36
+ * module recomputes the name from the display name instead of trusting what
37
+ * arrived, so the tree is the same whichever version of the instance-side code
38
+ * answered: it strips the id suffix the instance added (baseRecordName) and
39
+ * applies the whole rule again. Naming is therefore idempotent.
40
+ *
41
+ * One exception: a table whose name the project configured to carry the record's
42
+ * own id (tableOptions differentiatorField: "sys_id", or a nameTemplate). There
43
+ * a trailing ` (sys_id)` is the name that was asked for, not a suffix to strip,
44
+ * so those tables are named from the names as they arrive (`configuredNames`).
45
+ * Every record still gets its own folder; only the recomputation is skipped.
46
+ */
47
+ Object.defineProperty(exports, "__esModule", { value: true });
48
+ exports.assignFolderNames = exports.baseRecordName = exports.foldFolderName = exports.isSafeFolderName = exports.ID_SUFFIX_LENGTH = exports.FolderNameCollisionError = void 0;
49
+ /** Two records would share one folder and nothing tells them apart. */
50
+ class FolderNameCollisionError extends Error {
51
+ folder;
52
+ records;
53
+ constructor(folder, records) {
54
+ super("Cannot give these " + records.length + " records their own folder: they all resolve to '" +
55
+ folder + "' and no sys_id tells them apart (" +
56
+ records
57
+ .map(function (r) {
58
+ return "'" + r.name + "' sys_id " + (r.sys_id === "" ? "<none>" : r.sys_id);
59
+ })
60
+ .join(", ") +
61
+ "). Refusing to write one and drop the rest.");
62
+ this.name = "FolderNameCollisionError";
63
+ this.folder = folder;
64
+ this.records = records;
65
+ Object.setPrototypeOf(this, FolderNameCollisionError.prototype);
66
+ }
67
+ }
68
+ exports.FolderNameCollisionError = FolderNameCollisionError;
69
+ /** Characters of the sys_id in the suffix namesakes get. */
70
+ exports.ID_SUFFIX_LENGTH = 8;
71
+ /**
72
+ * Whether every supported disk can hold `name` as a folder. Windows forbids
73
+ * `< > : " | ? * \ /` in a path component, and a trailing space or dot.
74
+ */
75
+ const isSafeFolderName = (name) => {
76
+ return !(/[<>:"|?*\\/]/.test(name) || /[ .]$/.test(name) || name === "");
77
+ };
78
+ exports.isSafeFolderName = isSafeFolderName;
79
+ /**
80
+ * The form of a name under which two names are one folder on some disk: equal
81
+ * results mean a case-insensitive or normalization-insensitive disk cannot hold
82
+ * both. Upper then lower case approximates full Unicode case folding (ß and SS,
83
+ * long s and s); folding too much only adds a suffix, folding too little loses
84
+ * a record, so this errs towards more.
85
+ */
86
+ const foldFolderName = (name) => {
87
+ return String(name).normalize("NFC").toUpperCase().toLowerCase().normalize("NFC");
88
+ };
89
+ exports.foldFolderName = foldFolderName;
90
+ const idSuffix = (sysId, length) => {
91
+ return " (" + sysId.substring(0, length) + ")";
92
+ };
93
+ /**
94
+ * The display name a record's name was built from: `name` without the id
95
+ * suffix naming added. A suffix is a trailing ` (X)` where X is at least
96
+ * ID_SUFFIX_LENGTH characters long and is the start of the record's OWN sys_id,
97
+ * so parentheses in a display name, and another record's id, are left alone.
98
+ */
99
+ const baseRecordName = (name, sysId) => {
100
+ if (typeof name !== "string" || typeof sysId !== "string")
101
+ return typeof name === "string" ? name : "";
102
+ if (sysId === "" || name.charAt(name.length - 1) !== ")")
103
+ return name;
104
+ var open = name.lastIndexOf(" (");
105
+ if (open === -1)
106
+ return name;
107
+ var inner = name.substring(open + 2, name.length - 1);
108
+ if (inner.length < exports.ID_SUFFIX_LENGTH || sysId.indexOf(inner) !== 0)
109
+ return name;
110
+ return name.substring(0, open);
111
+ };
112
+ exports.baseRecordName = baseRecordName;
113
+ const groupBy = (items, keyOf) => {
114
+ var groups = new Map();
115
+ for (var i = 0; i < items.length; i++) {
116
+ var key = keyOf(items[i]);
117
+ var group = groups.get(key);
118
+ if (group)
119
+ group.push(items[i]);
120
+ else
121
+ groups.set(key, [items[i]]);
122
+ }
123
+ return groups;
124
+ };
125
+ const distinctIdentities = (group) => {
126
+ // A Set, not a plain object: an id is data and may be named "constructor".
127
+ var seen = new Set();
128
+ for (var i = 0; i < group.length; i++) {
129
+ seen.add(group[i].identity);
130
+ }
131
+ return seen.size;
132
+ };
133
+ const safeOrId = (folder, sysId) => {
134
+ // A record with no sys_id has no fallback; its name stands and the final
135
+ // check below refuses it if that leaves two records in one folder.
136
+ return (0, exports.isSafeFolderName)(folder) || sysId === "" ? folder : sysId;
137
+ };
138
+ /**
139
+ * Folder names for the records of one table, in input order.
140
+ *
141
+ * The answer depends only on the set of records, never on their order. One
142
+ * sys_id listed twice is one record and gets one name. No two different
143
+ * records ever get the same folder, compared the way the strictest disk
144
+ * compares: if that cannot be achieved (records without a sys_id that share a
145
+ * name), this throws FolderNameCollisionError rather than return a name that
146
+ * would drop a record.
147
+ */
148
+ const assignFolderNames = (records, options = {}) => {
149
+ if (!Array.isArray(records)) {
150
+ throw new TypeError("assignFolderNames expects an array of records");
151
+ }
152
+ var configuredNames = !!(options && options.configuredNames);
153
+ var candidates = [];
154
+ for (var i = 0; i < records.length; i++) {
155
+ var record = records[i];
156
+ var isRecord = record !== null && typeof record === "object";
157
+ var sysId = isRecord && typeof record.sys_id === "string" ? record.sys_id : "";
158
+ var name = isRecord && typeof record.name === "string" ? record.name : "";
159
+ candidates.push({
160
+ index: i,
161
+ identity: sysId === "" ? "#" + i : sysId,
162
+ sysId: sysId,
163
+ name: name,
164
+ base: configuredNames ? name : (0, exports.baseRecordName)(name, sysId),
165
+ folder: "",
166
+ });
167
+ }
168
+ // Steps 1 and 2: the display name, plus 8 id characters for namesakes.
169
+ groupBy(candidates, function (c) { return (0, exports.foldFolderName)(c.base); }).forEach(function (group) {
170
+ var shared = distinctIdentities(group) > 1;
171
+ for (var g = 0; g < group.length; g++) {
172
+ var c = group[g];
173
+ c.folder = safeOrId(shared ? c.base + idSuffix(c.sysId, exports.ID_SUFFIX_LENGTH) : c.base, c.sysId);
174
+ }
175
+ });
176
+ // Step 3: records still in one folder get their full id.
177
+ groupBy(candidates, function (c) { return (0, exports.foldFolderName)(c.folder); }).forEach(function (group) {
178
+ if (distinctIdentities(group) < 2)
179
+ return;
180
+ for (var g = 0; g < group.length; g++) {
181
+ var c = group[g];
182
+ c.folder = safeOrId(c.base + idSuffix(c.sysId, c.sysId.length), c.sysId);
183
+ }
184
+ });
185
+ // Nothing may be dropped: every folder belongs to exactly one record.
186
+ groupBy(candidates, function (c) { return (0, exports.foldFolderName)(c.folder); }).forEach(function (group, folded) {
187
+ if (distinctIdentities(group) < 2)
188
+ return;
189
+ throw new FolderNameCollisionError(group[0].folder === "" ? folded : group[0].folder, group.map(function (c) { return { name: c.name, sys_id: c.sysId }; }));
190
+ });
191
+ return candidates.map(function (c) { return c.folder; });
192
+ };
193
+ exports.assignFolderNames = assignFolderNames;
@@ -0,0 +1,167 @@
1
+ "use strict";
2
+ /**
3
+ * Which of the files a refresh wrote will git refuse to see?
4
+ *
5
+ * A record folder whose name matches an ignore rule (a client script named
6
+ * `console.log` under a `*.log` rule) is written to disk and then never staged:
7
+ * the record is missing from the repository and nothing said so. This asks git
8
+ * itself, so every source of ignore rules counts (nested .gitignore files,
9
+ * .git/info/exclude, the user's global excludes file) and a file git already
10
+ * tracks is never reported, because an ignore rule does not hide it.
11
+ *
12
+ * It lives in core, next to the writer: the refresh is the only code that knows
13
+ * every path it just wrote, and core already runs git for `--diff`. A repository
14
+ * hook could not report it, since an ignored path never reaches a commit.
15
+ *
16
+ * git is run without a shell and the paths go in on stdin, NUL-separated, so no
17
+ * record name is ever interpolated into a command line.
18
+ */
19
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
20
+ if (k2 === undefined) k2 = k;
21
+ var desc = Object.getOwnPropertyDescriptor(m, k);
22
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
23
+ desc = { enumerable: true, get: function() { return m[k]; } };
24
+ }
25
+ Object.defineProperty(o, k2, desc);
26
+ }) : (function(o, m, k, k2) {
27
+ if (k2 === undefined) k2 = k;
28
+ o[k2] = m[k];
29
+ }));
30
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
31
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
32
+ }) : function(o, v) {
33
+ o["default"] = v;
34
+ });
35
+ var __importStar = (this && this.__importStar) || (function () {
36
+ var ownKeys = function(o) {
37
+ ownKeys = Object.getOwnPropertyNames || function (o) {
38
+ var ar = [];
39
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
40
+ return ar;
41
+ };
42
+ return ownKeys(o);
43
+ };
44
+ return function (mod) {
45
+ if (mod && mod.__esModule) return mod;
46
+ var result = {};
47
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
48
+ __setModuleDefault(result, mod);
49
+ return result;
50
+ };
51
+ })();
52
+ var __importDefault = (this && this.__importDefault) || function (mod) {
53
+ return (mod && mod.__esModule) ? mod : { "default": mod };
54
+ };
55
+ Object.defineProperty(exports, "__esModule", { value: true });
56
+ exports.findGitIgnoredPaths = void 0;
57
+ const cp = __importStar(require("child_process"));
58
+ const path_1 = __importDefault(require("path"));
59
+ const runGit = (args, cwd, input) => {
60
+ return new Promise(function (resolve) {
61
+ var stdout = [];
62
+ var stderr = [];
63
+ var settled = false;
64
+ var finish = function (run) {
65
+ if (settled)
66
+ return;
67
+ settled = true;
68
+ resolve(run);
69
+ };
70
+ var child;
71
+ try {
72
+ // check-ignore reads each path literally (`[`, `*` and `:` in a folder
73
+ // name are not pattern syntax to it), so no pathspec switch is needed; it
74
+ // rejects GIT_LITERAL_PATHSPECS outright.
75
+ child = cp.spawn("git", args, { cwd: cwd, windowsHide: true });
76
+ }
77
+ catch (e) {
78
+ finish({ code: null, stdout: "", stderr: "", spawnError: e });
79
+ return;
80
+ }
81
+ child.stdout.on("data", function (chunk) { stdout.push(chunk); });
82
+ child.stderr.on("data", function (chunk) { stderr.push(chunk); });
83
+ child.on("error", function (err) {
84
+ finish({ code: null, stdout: "", stderr: "", spawnError: err });
85
+ });
86
+ child.on("close", function (code) {
87
+ finish({
88
+ code: code,
89
+ stdout: Buffer.concat(stdout).toString("utf8"),
90
+ stderr: Buffer.concat(stderr).toString("utf8"),
91
+ });
92
+ });
93
+ // git may exit before it has read everything (not a repository): a write
94
+ // to its closed stdin must not take the refresh down.
95
+ child.stdin.on("error", function () { });
96
+ child.stdin.end(input);
97
+ });
98
+ };
99
+ /**
100
+ * Asks git which of `filePaths` it ignores. `baseDir` is the directory the
101
+ * paths live under (the application's source folder); paths outside it are not
102
+ * asked about.
103
+ *
104
+ * Never throws: a refresh must not fail because git could not be asked.
105
+ */
106
+ const findGitIgnoredPaths = async (filePaths, baseDir) => {
107
+ if (!Array.isArray(filePaths) || typeof baseDir !== "string" || baseDir === "") {
108
+ return { ignored: [], checked: false };
109
+ }
110
+ // Relative to where git runs, with forward slashes: git then never has to
111
+ // reconcile a symlinked absolute prefix with its own idea of the work tree.
112
+ var relativeToAbsolute = new Map();
113
+ var relatives = [];
114
+ for (var i = 0; i < filePaths.length; i++) {
115
+ var absolute = filePaths[i];
116
+ if (typeof absolute !== "string" || absolute === "" || absolute.indexOf("\0") !== -1)
117
+ continue;
118
+ var relative = path_1.default.relative(baseDir, absolute);
119
+ if (relative === "" || relative.split(path_1.default.sep)[0] === ".." || path_1.default.isAbsolute(relative))
120
+ continue;
121
+ var forGit = relative.split(path_1.default.sep).join("/");
122
+ if (!relativeToAbsolute.has(forGit)) {
123
+ relativeToAbsolute.set(forGit, absolute);
124
+ relatives.push(forGit);
125
+ }
126
+ }
127
+ if (relatives.length === 0)
128
+ return { ignored: [], checked: true };
129
+ var run = await runGit(["check-ignore", "--verbose", "-z", "--stdin"], baseDir, relatives.join("\0") + "\0");
130
+ if (run.spawnError) {
131
+ // ENOENT: no git installed, or the source folder does not exist yet.
132
+ return { ignored: [], checked: false };
133
+ }
134
+ // 0: at least one path is ignored. 1: none is. Anything else is a failure.
135
+ if (run.code !== 0 && run.code !== 1) {
136
+ if (/not a git repository/i.test(run.stderr)) {
137
+ return { ignored: [], checked: false };
138
+ }
139
+ return {
140
+ ignored: [],
141
+ checked: false,
142
+ warning: "could not check git ignore rules under " + baseDir + ": " +
143
+ (run.stderr.trim().split(/\r?\n/)[0] || "git exited with code " + String(run.code)),
144
+ };
145
+ }
146
+ // --verbose -z prints <source> NUL <line> NUL <pattern> NUL <path> NUL per match.
147
+ var fields = run.stdout.split("\0");
148
+ var ignored = [];
149
+ for (var f = 0; f + 3 < fields.length; f += 4) {
150
+ var source = fields[f];
151
+ var line = fields[f + 1];
152
+ var pattern = fields[f + 2];
153
+ var reported = fields[f + 3];
154
+ // A match on a negated rule means the path is explicitly NOT ignored.
155
+ if (pattern === "" || pattern.charAt(0) === "!")
156
+ continue;
157
+ var asked = relativeToAbsolute.get(reported);
158
+ ignored.push({
159
+ path: asked !== undefined ? asked : path_1.default.join(baseDir, reported),
160
+ source: source,
161
+ line: line,
162
+ pattern: pattern,
163
+ });
164
+ }
165
+ return { ignored: ignored, checked: true };
166
+ };
167
+ exports.findGitIgnoredPaths = findGitIgnoredPaths;