tortoise-orm-studio 1.0.0__py3-none-any.whl

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.
Files changed (68) hide show
  1. tortoise_orm_studio/__init__.py +11 -0
  2. tortoise_orm_studio/adapters/__init__.py +1 -0
  3. tortoise_orm_studio/adapters/aiohttp_adapter.py +31 -0
  4. tortoise_orm_studio/adapters/asgi.py +89 -0
  5. tortoise_orm_studio/adapters/base.py +25 -0
  6. tortoise_orm_studio/adapters/django_adapter.py +84 -0
  7. tortoise_orm_studio/adapters/quart_adapter.py +32 -0
  8. tortoise_orm_studio/adapters/registry.py +39 -0
  9. tortoise_orm_studio/adapters/sanic_adapter.py +39 -0
  10. tortoise_orm_studio/auth.py +34 -0
  11. tortoise_orm_studio/cli.py +41 -0
  12. tortoise_orm_studio/core/__init__.py +1 -0
  13. tortoise_orm_studio/core/aerich.py +86 -0
  14. tortoise_orm_studio/core/ai.py +87 -0
  15. tortoise_orm_studio/core/audit.py +69 -0
  16. tortoise_orm_studio/core/config.py +58 -0
  17. tortoise_orm_studio/core/filters.py +94 -0
  18. tortoise_orm_studio/core/handler.py +249 -0
  19. tortoise_orm_studio/core/http.py +55 -0
  20. tortoise_orm_studio/core/i18n.py +18 -0
  21. tortoise_orm_studio/core/introspect.py +197 -0
  22. tortoise_orm_studio/core/manifest.py +128 -0
  23. tortoise_orm_studio/core/pagination.py +59 -0
  24. tortoise_orm_studio/core/permissions.py +46 -0
  25. tortoise_orm_studio/core/plugins.py +214 -0
  26. tortoise_orm_studio/core/ratelimit.py +32 -0
  27. tortoise_orm_studio/core/scoping.py +23 -0
  28. tortoise_orm_studio/core/serializers.py +61 -0
  29. tortoise_orm_studio/core/service.py +594 -0
  30. tortoise_orm_studio/plugins.py +8 -0
  31. tortoise_orm_studio/static/ALPINE_LICENSE.txt +11 -0
  32. tortoise_orm_studio/static/_types.d.ts +706 -0
  33. tortoise_orm_studio/static/a11y.js +115 -0
  34. tortoise_orm_studio/static/ai.js +66 -0
  35. tortoise_orm_studio/static/alpine.min.js +23 -0
  36. tortoise_orm_studio/static/app.css +514 -0
  37. tortoise_orm_studio/static/app.js +1443 -0
  38. tortoise_orm_studio/static/audit.js +171 -0
  39. tortoise_orm_studio/static/copy-as.js +118 -0
  40. tortoise_orm_studio/static/er-layout.js +227 -0
  41. tortoise_orm_studio/static/er.js +296 -0
  42. tortoise_orm_studio/static/filters.js +114 -0
  43. tortoise_orm_studio/static/i18n.en.js +190 -0
  44. tortoise_orm_studio/static/i18n.js +140 -0
  45. tortoise_orm_studio/static/i18n.zh-CN.js +189 -0
  46. tortoise_orm_studio/static/index.html +515 -0
  47. tortoise_orm_studio/static/inline-edit.js +107 -0
  48. tortoise_orm_studio/static/json-view.js +161 -0
  49. tortoise_orm_studio/static/migrations.js +139 -0
  50. tortoise_orm_studio/static/palette.js +141 -0
  51. tortoise_orm_studio/static/pending.js +240 -0
  52. tortoise_orm_studio/static/pickers.js +230 -0
  53. tortoise_orm_studio/static/playground.js +105 -0
  54. tortoise_orm_studio/static/query-history.js +84 -0
  55. tortoise_orm_studio/static/shortcuts.js +145 -0
  56. tortoise_orm_studio/static/state-hash.js +112 -0
  57. tortoise_orm_studio/static/tabs.js +368 -0
  58. tortoise_orm_studio/static/theme-init.js +33 -0
  59. tortoise_orm_studio/static/theme.js +106 -0
  60. tortoise_orm_studio/static/toasts.js +76 -0
  61. tortoise_orm_studio/static/views.js +70 -0
  62. tortoise_orm_studio/static/widgets.js +345 -0
  63. tortoise_orm_studio/studio.py +51 -0
  64. tortoise_orm_studio-1.0.0.dist-info/METADATA +177 -0
  65. tortoise_orm_studio-1.0.0.dist-info/RECORD +68 -0
  66. tortoise_orm_studio-1.0.0.dist-info/WHEEL +4 -0
  67. tortoise_orm_studio-1.0.0.dist-info/entry_points.txt +2 -0
  68. tortoise_orm_studio-1.0.0.dist-info/licenses/LICENSE +13 -0
@@ -0,0 +1,161 @@
1
+ // @ts-check
2
+ /**
3
+ * Collapsible JSON viewer/editor for v0.5.0 (UI program D).
4
+ *
5
+ * Builds a tree from an already-parsed value. Syntax colours are CSS classes
6
+ * only (no inline styles). Every node exposes copy-path / copy-value buttons
7
+ * wired with addEventListener; text is inserted via textContent so a hostile
8
+ * value can never become markup. Pure DOM construction — no state, no fetch.
9
+ *
10
+ * Types: JsonViewAPI in _types.d.ts.
11
+ */
12
+ (function (/** @type {any} */ global) {
13
+ "use strict";
14
+
15
+ /**
16
+ * @template {keyof HTMLElementTagNameMap} K
17
+ * @param {K} tag
18
+ * @param {Record<string, any>} props
19
+ * @param {Array<Node|string>} [children]
20
+ * @returns {HTMLElementTagNameMap[K]}
21
+ */
22
+ function create(tag, props, children) {
23
+ /** @type {any} */
24
+ const el = document.createElement(tag);
25
+ for (const k of Object.keys(props || {})) {
26
+ const v = props[k];
27
+ if (v === undefined) continue;
28
+ if (k === "class") el.className = v;
29
+ else if (k.startsWith("on") && typeof v === "function") el.addEventListener(k.slice(2), v);
30
+ else if (k in el) el[k] = v;
31
+ else el.setAttribute(k, String(v));
32
+ }
33
+ for (const c of children || []) {
34
+ el.appendChild(typeof c === "string" ? document.createTextNode(c) : c);
35
+ }
36
+ return el;
37
+ }
38
+
39
+ /** @param {any} v */
40
+ function kindOf(v) {
41
+ if (v === null) return "null";
42
+ if (Array.isArray(v)) return "array";
43
+ if (typeof v === "object") return "object";
44
+ if (typeof v === "boolean") return "bool";
45
+ if (typeof v === "number") return "number";
46
+ return "string";
47
+ }
48
+
49
+ /**
50
+ * @param {string} text
51
+ * @param {(ok: boolean) => void} done
52
+ */
53
+ function copy(text, done) {
54
+ const C = /** @type {any} */ (/** @type {any} */ (global).StudioCopyAs);
55
+ if (!C || typeof C.write !== "function") { done(false); return; }
56
+ C.write(text).then(done, /** @type {() => void} */ (function () { done(false); }));
57
+ }
58
+
59
+ /** @param {string} msg @param {"success"|"error"} level */
60
+ function toast(msg, level) {
61
+ const T = /** @type {any} */ (/** @type {any} */ (global).StudioToasts);
62
+ if (T && typeof T.show === "function") T.show(msg, level);
63
+ }
64
+
65
+ /**
66
+ * Parse text into a value; returns { ok, value?, error? }.
67
+ * @param {string} text
68
+ * @returns {{ok: boolean, value?: any, error?: string}}
69
+ */
70
+ function validate(text) {
71
+ try {
72
+ return { ok: true, value: JSON.parse(text) };
73
+ } catch (e) {
74
+ return { ok: false, error: e instanceof Error ? e.message : String(e) };
75
+ }
76
+ }
77
+
78
+ /**
79
+ * @param {string} path
80
+ * @param {string} label
81
+ * @param {any} value
82
+ * @returns {HTMLElement}
83
+ */
84
+ function leaf(path, label, value) {
85
+ const kind = kindOf(value);
86
+ const shown = value === null ? "null" : typeof value === "string"
87
+ ? JSON.stringify(value) : String(value);
88
+ const row = create("div", { class: "jv-row jv-" + kind });
89
+ row.appendChild(create("span", { class: "jv-key", textContent: label }));
90
+ row.appendChild(create("span", { class: "jv-sep", textContent: ":" }));
91
+ const val = create("span", { class: "jv-value jv-val-" + kind, textContent: shown });
92
+ row.appendChild(val);
93
+ row.appendChild(create("button", {
94
+ type: "button", class: "jv-copy", "aria-label": "Copy path " + path,
95
+ onclick: function () {
96
+ copy(path, function (ok) { toast(ok ? "Copied path" : "Copy failed", ok ? "success" : "error"); });
97
+ },
98
+ }, ["path"]));
99
+ row.appendChild(create("button", {
100
+ type: "button", class: "jv-copy", "aria-label": "Copy value " + path,
101
+ onclick: function () {
102
+ const raw = typeof value === "string" ? value : JSON.stringify(value);
103
+ copy(raw, function (ok) { toast(ok ? "Copied value" : "Copy failed", ok ? "success" : "error"); });
104
+ },
105
+ }, ["value"]));
106
+ return row;
107
+ }
108
+
109
+ /**
110
+ * @param {string} label
111
+ * @param {any} value
112
+ * @param {(base: string, key: string) => string} join
113
+ * @param {string} path
114
+ * @param {number} depth
115
+ * @returns {HTMLElement}
116
+ */
117
+ function node(label, value, join, path, depth) {
118
+ const kind = kindOf(value);
119
+ if (kind !== "object" && kind !== "array") return leaf(path, label, value);
120
+ const keys = Object.keys(value);
121
+ const details = create("details", { class: "jv-node jv-" + kind, open: depth < 1 });
122
+ const summary = create("summary", { class: "jv-summary" });
123
+ summary.appendChild(create("span", { class: "jv-key", textContent: label }));
124
+ summary.appendChild(create("span", {
125
+ class: "jv-count", textContent: " " + (kind === "array" ? "[" + keys.length + "]" : "{" + keys.length + "}"),
126
+ }));
127
+ summary.appendChild(create("button", {
128
+ type: "button", class: "jv-copy", "aria-label": "Copy path " + path,
129
+ onclick: function (/** @type {Event} */ e) {
130
+ e.preventDefault();
131
+ copy(path, function (ok) { toast(ok ? "Copied path" : "Copy failed", ok ? "success" : "error"); });
132
+ },
133
+ }, ["path"]));
134
+ details.appendChild(summary);
135
+ const body = create("div", { class: "jv-children" });
136
+ details.appendChild(body);
137
+ for (const k of keys) {
138
+ const childPath = join(path, kind === "array" ? "[" + k + "]" : k);
139
+ body.appendChild(node(k, value[k], join, childPath, depth + 1));
140
+ }
141
+ return details;
142
+ }
143
+
144
+ /**
145
+ * @param {any} value
146
+ * @param {{ rootLabel?: string }} [options]
147
+ * @returns {HTMLElement}
148
+ */
149
+ function render(value, options) {
150
+ const opts = options || {};
151
+ const root = create("div", { class: "json-view" });
152
+ const dot = function (/** @type {string} */ base, /** @type {string} */ key) {
153
+ if (key.charAt(0) === "[") return base + key;
154
+ return base ? base + "." + key : key;
155
+ };
156
+ root.appendChild(node(opts.rootLabel || "root", value, dot, opts.rootLabel || "root", 0));
157
+ return root;
158
+ }
159
+
160
+ global.StudioJsonView = { render: render, validate: validate, kindOf: kindOf };
161
+ })((typeof window !== "undefined" ? window : globalThis));
@@ -0,0 +1,139 @@
1
+ // @ts-check
2
+ /**
3
+ * Renders the migration panel from GET /api/migrations.
4
+ *
5
+ * Exposes window.StudioMigrations.render(info).
6
+ * Shows applied + pending tables, connection name, migrations dir.
7
+ *
8
+ * Types: MigrationsInfo, MigrationsAPI from _types.d.ts.
9
+ */
10
+
11
+ (function (/** @type {Window & { StudioMigrations?: MigrationsAPI }} */ global) {
12
+ "use strict";
13
+
14
+ /**
15
+ * @template {keyof HTMLElementTagNameMap} K
16
+ * @param {K} tag
17
+ * @param {Record<string, any>} [props]
18
+ * @param {Array<Node|string>} [children]
19
+ * @returns {HTMLElementTagNameMap[K]}
20
+ */
21
+ function create(tag, props, children) {
22
+ /** @type {any} */
23
+ const el = document.createElement(tag);
24
+ for (const k of Object.keys(props || {})) {
25
+ const v = props[k];
26
+ if (v === undefined) continue;
27
+ if (k === "class") el.className = v;
28
+ else if (k.startsWith("on") && typeof v === "function") el.addEventListener(k.slice(2), v);
29
+ else if (k in el) el[k] = v;
30
+ else el.setAttribute(k, String(v));
31
+ }
32
+ for (const c of children || []) {
33
+ el.appendChild(typeof c === "string" ? document.createTextNode(c) : c);
34
+ }
35
+ return el;
36
+ }
37
+
38
+ /**
39
+ * @param {string[]} headers
40
+ * @param {string[][]} rows
41
+ * @param {string} kind
42
+ * @returns {HTMLElement}
43
+ */
44
+ function buildTable(headers, rows, kind) {
45
+ const table = create("table", { class: "migrations-table " + kind });
46
+ const thead = create("thead");
47
+ const headRow = create("tr");
48
+ for (const h of headers) headRow.appendChild(create("th", {}, [h]));
49
+ thead.appendChild(headRow);
50
+ table.appendChild(thead);
51
+
52
+ const tbody = create("tbody");
53
+ for (const row of rows) {
54
+ const tr = create("tr");
55
+ for (const cell of row) tr.appendChild(create("td", {}, [String(cell)]));
56
+ tbody.appendChild(tr);
57
+ }
58
+ table.appendChild(tbody);
59
+ return table;
60
+ }
61
+
62
+ /**
63
+ * @param {MigrationsInfo | null} info
64
+ * @param {{ available: boolean, connection: string | null, pending: Array<{ app: string, version: string, file: string }> }} [pendingInfo]
65
+ * @returns {HTMLElement}
66
+ */
67
+ function render(info, pendingInfo) {
68
+ const root = create("div", { class: "migrations-panel" });
69
+
70
+ if (!info) {
71
+ root.appendChild(create("p", { class: "mut" }, ["Loading…"]));
72
+ return root;
73
+ }
74
+
75
+ if (!info.available) {
76
+ root.appendChild(create("p", { class: "mut" }, [
77
+ "No aerich table found in this database.",
78
+ ]));
79
+ root.appendChild(create("p", { class: "mut" }, [
80
+ "Install aerich and run `aerich init-db` in your project to enable migration tracking.",
81
+ ]));
82
+ return root;
83
+ }
84
+
85
+ const meta = create("div", { class: "migrations-meta" });
86
+ if (info.connection) {
87
+ const p = create("p");
88
+ p.appendChild(create("strong", {}, ["Connection: "]));
89
+ p.appendChild(document.createTextNode(info.connection));
90
+ meta.appendChild(p);
91
+ }
92
+ if (info.migrations_dir) {
93
+ const p = create("p");
94
+ p.appendChild(create("strong", {}, ["Migrations: "]));
95
+ p.appendChild(document.createTextNode(info.migrations_dir));
96
+ meta.appendChild(p);
97
+ }
98
+ root.appendChild(meta);
99
+
100
+ // The dedicated /api/migrations/pending route is the source of truth for
101
+ // the badge; the full view still drives the tables below.
102
+ if (pendingInfo) {
103
+ const n = pendingInfo.pending.length;
104
+ const badge = create("span", {
105
+ class: "migrations-pending-badge" + (n ? " has-pending" : ""),
106
+ role: "status",
107
+ }, [n ? n + " pending" : "up to date"]);
108
+ root.appendChild(badge);
109
+ }
110
+
111
+ const applied = info.applied || [];
112
+ root.appendChild(create("h4", {}, ["Applied (" + applied.length + ")"]));
113
+ if (applied.length) {
114
+ root.appendChild(buildTable(
115
+ ["App", "Version"],
116
+ applied.map(function (r) { return [r.app, r.version]; }),
117
+ "applied"
118
+ ));
119
+ } else {
120
+ root.appendChild(create("p", { class: "mut" }, ["None applied yet."]));
121
+ }
122
+
123
+ const pending = info.pending || [];
124
+ if (pending.length) {
125
+ root.appendChild(create("h4", { class: "pending" }, ["Pending (" + pending.length + ")"]));
126
+ root.appendChild(buildTable(
127
+ ["App", "Version", "File"],
128
+ pending.map(function (r) { return [r.app, r.version, r.file]; }),
129
+ "pending"
130
+ ));
131
+ } else if (info.migrations_dir) {
132
+ root.appendChild(create("p", { class: "mut" }, ["No pending migrations."]));
133
+ }
134
+
135
+ return root;
136
+ }
137
+
138
+ global.StudioMigrations = { render: render };
139
+ })(window);
@@ -0,0 +1,141 @@
1
+ // @ts-check
2
+ /**
3
+ * Command palette (Ctrl/Cmd+K) — program B, v0.3.3.
4
+ *
5
+ * Pure command-list building lives in `commands()`; `render()` builds DOM
6
+ * with createElement (no innerHTML, no inline styles) and wires keyboard
7
+ * selection. The fuzzy scorer is the tested `StudioShortcuts.search`.
8
+ */
9
+ (function (/** @type {Window & { StudioPalette?: PaletteAPI, StudioShortcuts?: any }} */ global) {
10
+ "use strict";
11
+
12
+ /**
13
+ * @template {keyof HTMLElementTagNameMap} K
14
+ * @param {K} tag
15
+ * @param {Record<string, any>} props
16
+ * @param {Array<Node|string>} [children]
17
+ * @returns {HTMLElementTagNameMap[K]}
18
+ */
19
+ function create(tag, props, children) {
20
+ /** @type {any} */ const el = document.createElement(tag);
21
+ for (const k of Object.keys(props || {})) {
22
+ const v = props[k];
23
+ if (v === undefined) continue;
24
+ if (k === "class") el.className = v;
25
+ else if (k.startsWith("on") && typeof v === "function") el.addEventListener(k.slice(2), v);
26
+ else if (k in el) el[k] = v;
27
+ else el.setAttribute(k, String(v));
28
+ }
29
+ for (const c of children || []) el.appendChild(typeof c === "string" ? document.createTextNode(c) : c);
30
+ return el;
31
+ }
32
+
33
+ /**
34
+ * Build the palette command list from the schema and current state.
35
+ * @param {Schema | null} schema
36
+ * @param {{ canWrite?: boolean, hasSavedViews?: boolean }} [flags]
37
+ * @returns {PaletteCommand[]}
38
+ */
39
+ function commands(schema, flags) {
40
+ const options = flags || {};
41
+ /** @type {PaletteCommand[]} */
42
+ const out = [];
43
+ for (const m of (schema && schema.models) || []) {
44
+ out.push({ id: "model:" + m.key, title: m.key, group: "Models", action: "open_model", arg: m.key });
45
+ }
46
+ out.push({ id: "new", title: "New row", group: "Actions", action: "new_row" });
47
+ out.push({ id: "explore", title: "Open query playground", group: "Actions", action: "open_playground" });
48
+ out.push({ id: "er", title: "Open ER diagram", group: "Actions", action: "open_er" });
49
+ out.push({ id: "migrations", title: "Open migrations", group: "Actions", action: "open_migrations" });
50
+ out.push({ id: "audit", title: "Open audit log", group: "Actions", action: "open_audit" });
51
+ out.push({ id: "theme", title: "Toggle theme", group: "Actions", action: "toggle_theme" });
52
+ if (options.hasSavedViews) out.push({ id: "views", title: "Saved views", group: "Actions", action: "saved_views" });
53
+ return out;
54
+ }
55
+
56
+ /**
57
+ * @param {PaletteCommand[]} commands
58
+ * @param {string} query
59
+ * @returns {PaletteCommand[]}
60
+ */
61
+ function filter(commands, query) {
62
+ const S = global.StudioShortcuts;
63
+ if (!query.trim()) return commands;
64
+ return S ? S.search(commands, query, 30) : commands.filter(function (c) {
65
+ return c.title.toLowerCase().includes(query.toLowerCase());
66
+ });
67
+ }
68
+
69
+ /**
70
+ * Render the palette. `onRun(command)` is called on Enter/click.
71
+ * @param {PaletteCommand[]} all
72
+ * @param {{ onRun: (c: PaletteCommand) => void, onClose?: () => void }} handlers
73
+ * @returns {HTMLElement}
74
+ */
75
+ function render(all, handlers) {
76
+ const root = create("div", { class: "palette", role: "dialog", "aria-modal": "true",
77
+ "aria-label": "Command palette" });
78
+ const input = create("input", { type: "text", class: "palette-input",
79
+ placeholder: "Type a model or command…", "aria-label": "Search commands",
80
+ autocomplete: "off", spellcheck: false });
81
+ const list = create("ul", { class: "palette-list", role: "listbox",
82
+ "aria-label": "Commands", tabindex: "0" });
83
+ /** @type {PaletteCommand[]} */
84
+ let shown = [];
85
+ let selected = 0;
86
+
87
+ /** @param {PaletteCommand | null} cmd */
88
+ function highlight(cmd) {
89
+ for (const li of Array.from(list.children)) li.classList.remove("selected");
90
+ if (!cmd) return;
91
+ const node = list.querySelector('[data-id="' + cmd.id.replace(/"/g, "") + '"]');
92
+ if (node) {
93
+ node.classList.add("selected");
94
+ node.setAttribute("aria-selected", "true");
95
+ node.scrollIntoView && node.scrollIntoView({ block: "nearest" });
96
+ }
97
+ }
98
+
99
+ function paint() {
100
+ list.replaceChildren();
101
+ shown = filter(all, input.value);
102
+ if (selected >= shown.length) selected = 0;
103
+ shown.forEach(function (cmd, i) {
104
+ const li = create("li", { class: "palette-item" + (i === selected ? " selected" : ""),
105
+ role: "option", "aria-selected": i === selected ? "true" : "false",
106
+ "data-id": cmd.id });
107
+ li.appendChild(create("span", { class: "palette-group" }, [cmd.group]));
108
+ li.appendChild(create("span", { class: "palette-title" }, [cmd.title]));
109
+ li.addEventListener("click", function () { handlers.onRun(cmd); });
110
+ list.appendChild(li);
111
+ });
112
+ if (!shown.length) list.appendChild(create("li", { class: "palette-empty" }, ["No matches"]));
113
+ }
114
+
115
+ input.addEventListener("input", function () { selected = 0; paint(); });
116
+ input.addEventListener("keydown", function (/** @type {any} */ ev) {
117
+ if (ev.key === "ArrowDown") {
118
+ ev.preventDefault();
119
+ selected = Math.min(shown.length - 1, selected + 1);
120
+ paint(); highlight(shown[selected] || null);
121
+ } else if (ev.key === "ArrowUp") {
122
+ ev.preventDefault();
123
+ selected = Math.max(0, selected - 1);
124
+ paint(); highlight(shown[selected] || null);
125
+ } else if (ev.key === "Enter") {
126
+ ev.preventDefault();
127
+ if (shown[selected]) handlers.onRun(shown[selected]);
128
+ } else if (ev.key === "Escape") {
129
+ ev.preventDefault();
130
+ if (handlers.onClose) handlers.onClose();
131
+ }
132
+ });
133
+
134
+ root.appendChild(input);
135
+ root.appendChild(list);
136
+ paint();
137
+ return root;
138
+ }
139
+
140
+ global.StudioPalette = { commands: commands, filter: filter, render: render };
141
+ })(window);
@@ -0,0 +1,240 @@
1
+ // @ts-check
2
+ /**
3
+ * Pure staged-changes store for v0.5.0 (UI program G2).
4
+ *
5
+ * No DOM, no storage, no network: every operation is a plain function over a
6
+ * plain object, so the whole feature is testable with `node --test`. The store
7
+ * only describes writes; `requestBody()` maps it to the `/api/v1/batch`
8
+ * contract. Nothing here ever talks to the server or persists row data.
9
+ *
10
+ * Types: PendingStore, PendingChange, BatchOp, BatchRequest in _types.d.ts.
11
+ */
12
+ (function (/** @type {any} */ global) {
13
+ "use strict";
14
+
15
+ /**
16
+ * @typedef {"create"|"update"|"delete"|"m2m_add"|"m2m_remove"} BatchOpName
17
+ * @typedef {{ id: string, seq: number, op: BatchOpName, model: string,
18
+ * pk?: string, data?: Record<string, any>, before?: Record<string, any>,
19
+ * expected?: Record<string, any>, rel?: string, ids?: string[] }} PendingChange
20
+ * @typedef {{ changes: PendingChange[], seq: number }} PendingStore
21
+ */
22
+
23
+ /** @returns {PendingStore} */
24
+ function create() {
25
+ return { changes: [], seq: 0 };
26
+ }
27
+
28
+ /** @param {PendingStore} store @returns {boolean} */
29
+ function isDirty(store) {
30
+ return store.changes.length > 0;
31
+ }
32
+
33
+ /**
34
+ * Stringify a primary key without losing leading zeroes.
35
+ * @param {any} pk
36
+ * @returns {string}
37
+ */
38
+ function pkString(pk) {
39
+ return pk === null || pk === undefined ? "" : String(pk);
40
+ }
41
+
42
+ /**
43
+ * @param {any[]} ids
44
+ * @returns {string[]}
45
+ */
46
+ function idList(ids) {
47
+ /** @type {string[]} */
48
+ var out = [];
49
+ for (var i = 0; i < ids.length; i++) {
50
+ var s = String(ids[i]);
51
+ if (out.indexOf(s) < 0) out.push(s);
52
+ }
53
+ return out;
54
+ }
55
+
56
+ /**
57
+ * Stage one write. Re-staging an update or delete for the same row merges
58
+ * into the existing change, so the panel shows one diff per row. A delete
59
+ * supersedes a staged update; a staged m2m add/remove merges by relation and
60
+ * cancels out the inverse operation for the same targets.
61
+ *
62
+ * @param {PendingStore} store
63
+ * @param {any} spec
64
+ * @returns {{ store: PendingStore, change: PendingChange | null, coalesced: boolean }}
65
+ */
66
+ function stage(store, spec) {
67
+ var op = /** @type {BatchOpName} */ (spec && spec.op);
68
+ if (!spec || ["create", "update", "delete", "m2m_add", "m2m_remove"].indexOf(op) < 0) {
69
+ throw new Error("unknown batch operation: " + op);
70
+ }
71
+ if (typeof spec.model !== "string" || !spec.model) {
72
+ throw new Error("operation.model is required");
73
+ }
74
+ if (op !== "create" && (spec.pk === null || spec.pk === undefined || spec.pk === "")) {
75
+ throw new Error("operation.pk is required for " + op);
76
+ }
77
+
78
+ var changes = store.changes.slice();
79
+ var seq = store.seq;
80
+ var pk = pkString(spec.pk);
81
+ var next = function () {
82
+ seq += 1;
83
+ return "p" + seq.toString(36);
84
+ };
85
+ var coalesced = false;
86
+ var change = /** @type {PendingChange} */ ({ id: next(), seq: seq, op: op, model: spec.model });
87
+
88
+ if (op === "create") {
89
+ change.data = Object.assign({}, spec.data || {});
90
+ change.before = {};
91
+ changes.push(change);
92
+ } else if (op === "update") {
93
+ var existing = changes.find(function (/** @type {PendingChange} */ c) {
94
+ return c.op === "update" && c.model === spec.model && c.pk === pk;
95
+ });
96
+ if (existing) {
97
+ existing.data = Object.assign({}, existing.data || {}, spec.data || {});
98
+ if (spec.expected) existing.expected = Object.assign({}, existing.expected || {}, spec.expected);
99
+ change = existing;
100
+ coalesced = true;
101
+ } else {
102
+ change.pk = pk;
103
+ change.data = Object.assign({}, spec.data || {});
104
+ change.before = Object.assign({}, spec.before || {});
105
+ if (spec.expected) change.expected = Object.assign({}, spec.expected);
106
+ changes.push(change);
107
+ }
108
+ } else if (op === "delete") {
109
+ var priorUpdate = changes.findIndex(function (/** @type {PendingChange} */ c) {
110
+ return c.op === "update" && c.model === spec.model && c.pk === pk;
111
+ });
112
+ if (priorUpdate >= 0) changes.splice(priorUpdate, 1);
113
+ var priorDelete = changes.find(function (/** @type {PendingChange} */ c) {
114
+ return c.op === "delete" && c.model === spec.model && c.pk === pk;
115
+ });
116
+ if (priorDelete) {
117
+ change = priorDelete;
118
+ coalesced = true;
119
+ } else {
120
+ change.pk = pk;
121
+ change.before = Object.assign({}, spec.before || {});
122
+ changes.push(change);
123
+ }
124
+ } else {
125
+ // m2m_add / m2m_remove
126
+ change.pk = pk;
127
+ change.rel = spec.rel;
128
+ change.ids = idList(spec.ids || []);
129
+ var inverse = op === "m2m_add" ? "m2m_remove" : "m2m_add";
130
+ var opposite = changes.find(function (/** @type {PendingChange} */ c) {
131
+ return c.op === inverse && c.model === spec.model && c.pk === pk && c.rel === spec.rel;
132
+ });
133
+ if (opposite && opposite.ids) {
134
+ // An add then a remove of the same target is a no-op: cancel the
135
+ // overlap from both changes, then drop whichever becomes empty.
136
+ var overlap = change.ids.filter(function (/** @type {string} */ id) {
137
+ return opposite.ids && opposite.ids.indexOf(id) >= 0;
138
+ });
139
+ opposite.ids = opposite.ids.filter(function (/** @type {string} */ id) {
140
+ return overlap.indexOf(id) < 0;
141
+ });
142
+ change.ids = change.ids.filter(function (/** @type {string} */ id) {
143
+ return overlap.indexOf(id) < 0;
144
+ });
145
+ if (!opposite.ids.length) {
146
+ changes.splice(changes.indexOf(opposite), 1);
147
+ }
148
+ }
149
+ var same = changes.find(function (/** @type {PendingChange} */ c) {
150
+ return c.op === op && c.model === spec.model && c.pk === pk && c.rel === spec.rel;
151
+ });
152
+ if (same && same.ids) {
153
+ same.ids = idList(same.ids.concat(change.ids));
154
+ change = same;
155
+ coalesced = true;
156
+ } else if (change.ids.length) {
157
+ changes.push(change);
158
+ }
159
+ }
160
+
161
+ return { store: { changes: changes, seq: seq }, change: change, coalesced: coalesced };
162
+ }
163
+
164
+ /**
165
+ * @param {PendingStore} store
166
+ * @param {string} id
167
+ * @returns {PendingStore}
168
+ */
169
+ function discard(store, id) {
170
+ return {
171
+ seq: store.seq,
172
+ changes: store.changes.filter(function (/** @type {PendingChange} */ c) { return c.id !== id; }),
173
+ };
174
+ }
175
+
176
+ /** @param {PendingStore} store @returns {PendingStore} */
177
+ function discardAll(store) {
178
+ return { changes: [], seq: store.seq };
179
+ }
180
+
181
+ /** @param {PendingStore} store @returns {PendingStore} */
182
+ function undo(store) {
183
+ if (!store.changes.length) return store;
184
+ var last = store.changes[store.changes.length - 1];
185
+ return discard(store, last.id);
186
+ }
187
+
188
+ /**
189
+ * Field-level diff for the Pending changes panel.
190
+ * @param {PendingChange} change
191
+ * @returns {{ field: string, before: any, after: any }[]}
192
+ */
193
+ function diff(change) {
194
+ /** @type {{ field: string, before: any, after: any }[]} */
195
+ var out = [];
196
+ var data = change.data || {};
197
+ var before = change.before || {};
198
+ if (change.op === "delete") return out;
199
+ for (var field of Object.keys(data)) {
200
+ var after = data[field];
201
+ var prior = before[field];
202
+ if (JSON.stringify(prior) !== JSON.stringify(after)) {
203
+ out.push({ field: field, before: prior === undefined ? null : prior, after: after });
204
+ }
205
+ }
206
+ return out;
207
+ }
208
+
209
+ /**
210
+ * Map the store to the POST /api/v1/batch request body. UI-only keys
211
+ * (`id`, `seq`, `before`) never leave the browser.
212
+ *
213
+ * @param {PendingStore} store
214
+ * @param {string} [connection]
215
+ * @returns {BatchRequest}
216
+ */
217
+ function requestBody(store, connection) {
218
+ /** @type {any[]} */
219
+ var operations = [];
220
+ for (var change of store.changes) {
221
+ /** @type {any} */
222
+ var op = { op: change.op, model: change.model };
223
+ if (change.pk !== undefined) op.pk = change.pk;
224
+ if (change.data !== undefined) op.data = change.data;
225
+ if (change.expected !== undefined) op.expected = change.expected;
226
+ if (change.rel !== undefined) op.rel = change.rel;
227
+ if (change.ids !== undefined) op.ids = change.ids.slice();
228
+ operations.push(op);
229
+ }
230
+ /** @type {BatchRequest} */
231
+ var body = { operations: operations };
232
+ if (connection) body.connection = connection;
233
+ return body;
234
+ }
235
+
236
+ global.StudioPending = {
237
+ create: create, isDirty: isDirty, stage: stage, discard: discard,
238
+ discardAll: discardAll, undo: undo, diff: diff, requestBody: requestBody,
239
+ };
240
+ })(typeof window !== "undefined" ? window : globalThis);