@superbee/core 0.1.6 → 0.2.0-pre.1

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 (105) hide show
  1. package/dist/backend.d.ts.map +1 -1
  2. package/dist/backend.js +29 -7
  3. package/dist/backend.js.map +1 -1
  4. package/dist/bundle-ops.d.ts +42 -0
  5. package/dist/bundle-ops.d.ts.map +1 -0
  6. package/dist/bundle-ops.js +88 -0
  7. package/dist/bundle-ops.js.map +1 -0
  8. package/dist/bundle.d.ts +8 -27
  9. package/dist/bundle.d.ts.map +1 -1
  10. package/dist/bundle.js +9 -66
  11. package/dist/bundle.js.map +1 -1
  12. package/dist/document-field-actions.d.ts +95 -0
  13. package/dist/document-field-actions.d.ts.map +1 -0
  14. package/dist/document-field-actions.js +261 -0
  15. package/dist/document-field-actions.js.map +1 -0
  16. package/dist/document-mutation.d.ts +46 -2
  17. package/dist/document-mutation.d.ts.map +1 -1
  18. package/dist/document-mutation.js +79 -19
  19. package/dist/document-mutation.js.map +1 -1
  20. package/dist/document-write-policy.d.ts +0 -1
  21. package/dist/document-write-policy.d.ts.map +1 -1
  22. package/dist/document-write-policy.js +3 -2
  23. package/dist/document-write-policy.js.map +1 -1
  24. package/dist/engine.d.ts +2 -0
  25. package/dist/engine.d.ts.map +1 -1
  26. package/dist/engine.js +2 -1
  27. package/dist/engine.js.map +1 -1
  28. package/dist/freshness.d.ts +10 -7
  29. package/dist/freshness.d.ts.map +1 -1
  30. package/dist/freshness.js +14 -11
  31. package/dist/freshness.js.map +1 -1
  32. package/dist/frontmatter-contract.d.ts +2 -2
  33. package/dist/frontmatter-contract.js +2 -2
  34. package/dist/frontmatter.d.ts +3 -1
  35. package/dist/frontmatter.d.ts.map +1 -1
  36. package/dist/frontmatter.js +7 -4
  37. package/dist/frontmatter.js.map +1 -1
  38. package/dist/index.d.ts +10 -3
  39. package/dist/index.d.ts.map +1 -1
  40. package/dist/index.js +12 -2
  41. package/dist/index.js.map +1 -1
  42. package/dist/indexeddb-backend.d.ts +165 -0
  43. package/dist/indexeddb-backend.d.ts.map +1 -0
  44. package/dist/indexeddb-backend.js +718 -0
  45. package/dist/indexeddb-backend.js.map +1 -0
  46. package/dist/journaled-backend.d.ts +178 -0
  47. package/dist/journaled-backend.d.ts.map +1 -0
  48. package/dist/journaled-backend.js +77 -0
  49. package/dist/journaled-backend.js.map +1 -0
  50. package/dist/kind-field-mutation.d.ts +15 -0
  51. package/dist/kind-field-mutation.d.ts.map +1 -0
  52. package/dist/kind-field-mutation.js +160 -0
  53. package/dist/kind-field-mutation.js.map +1 -0
  54. package/dist/kinds.d.ts.map +1 -1
  55. package/dist/kinds.js +3 -1
  56. package/dist/kinds.js.map +1 -1
  57. package/dist/meaningful-change-time.d.ts +6 -6
  58. package/dist/meaningful-change-time.d.ts.map +1 -1
  59. package/dist/meaningful-change-time.js +12 -13
  60. package/dist/meaningful-change-time.js.map +1 -1
  61. package/dist/mutation.d.ts.map +1 -1
  62. package/dist/mutation.js +2 -2
  63. package/dist/mutation.js.map +1 -1
  64. package/dist/page.d.ts.map +1 -1
  65. package/dist/page.js +2 -1
  66. package/dist/page.js.map +1 -1
  67. package/dist/platform.d.ts +161 -0
  68. package/dist/platform.d.ts.map +1 -0
  69. package/dist/platform.js +77 -0
  70. package/dist/platform.js.map +1 -0
  71. package/dist/recipes.d.ts +3 -1
  72. package/dist/recipes.d.ts.map +1 -1
  73. package/dist/recipes.js +4 -4
  74. package/dist/recipes.js.map +1 -1
  75. package/dist/remote-backend.d.ts +28 -0
  76. package/dist/remote-backend.d.ts.map +1 -1
  77. package/dist/remote-backend.js +75 -2
  78. package/dist/remote-backend.js.map +1 -1
  79. package/dist/remote-operations.d.ts +60 -0
  80. package/dist/remote-operations.d.ts.map +1 -0
  81. package/dist/remote-operations.js +110 -0
  82. package/dist/remote-operations.js.map +1 -0
  83. package/dist/sha256.d.ts +21 -0
  84. package/dist/sha256.d.ts.map +1 -0
  85. package/dist/sha256.js +114 -0
  86. package/dist/sha256.js.map +1 -0
  87. package/dist/storage.d.ts +5 -1
  88. package/dist/storage.d.ts.map +1 -1
  89. package/dist/storage.js +7 -1
  90. package/dist/storage.js.map +1 -1
  91. package/dist/types.d.ts +12 -0
  92. package/dist/types.d.ts.map +1 -1
  93. package/dist/uncertain-write.d.ts +142 -0
  94. package/dist/uncertain-write.d.ts.map +1 -0
  95. package/dist/uncertain-write.js +174 -0
  96. package/dist/uncertain-write.js.map +1 -0
  97. package/dist/version-transport.d.ts +7 -0
  98. package/dist/version-transport.d.ts.map +1 -1
  99. package/dist/version-transport.js +9 -0
  100. package/dist/version-transport.js.map +1 -1
  101. package/dist/versioning.d.ts +9 -3
  102. package/dist/versioning.d.ts.map +1 -1
  103. package/dist/versioning.js +14 -10
  104. package/dist/versioning.js.map +1 -1
  105. package/package.json +42 -3
@@ -0,0 +1,261 @@
1
+ /** Explicit frontmatter intent. Collection construction is owned here, before CAS metadata. */
2
+ import { InvalidInputError } from "./errors.js";
3
+ import { okfValuesEqual } from "./okf-authored-values.js";
4
+ import { kindInputFieldNames, resolveKindFieldCoordinate } from "./kinds.js";
5
+ /** Adapters can render corrective commands without parsing prose or repeating selection. */
6
+ export class FieldActionError extends InvalidInputError {
7
+ details;
8
+ constructor(message, details) {
9
+ super(message);
10
+ this.name = "FieldActionError";
11
+ this.details = details;
12
+ }
13
+ }
14
+ const managed = new Set(["generated", "verified", "superbee_updated_by", "actor", "timestamp"]);
15
+ const standard = new Set(["title", "description", "type", "resource"]);
16
+ const v02 = new Set(["status", "stale_after", "usage_window"]);
17
+ export function isStandardDocumentSetField(field, okfVersion) {
18
+ return standard.has(field) || (okfVersion === "0.2" && v02.has(field));
19
+ }
20
+ function record(value) {
21
+ return value !== null && typeof value === "object" && !Array.isArray(value);
22
+ }
23
+ function has(object, key) { return Object.prototype.hasOwnProperty.call(object, key); }
24
+ function sourceCandidates(rows) {
25
+ return {
26
+ total: rows.length,
27
+ candidates: rows.slice(0, 5).map(row => {
28
+ const identity = {};
29
+ for (const key of ["id", "resource", "title"]) {
30
+ if (record(row) && has(row, key) && typeof row[key] === "string")
31
+ identity[key] = row[key];
32
+ }
33
+ return identity;
34
+ }),
35
+ };
36
+ }
37
+ export function containsCollection(value) {
38
+ return Array.isArray(value) || (record(value) && Object.values(value).some(containsCollection));
39
+ }
40
+ export function assertNonCollectionAssignment(field, previous, value) {
41
+ if (containsCollection(previous) || containsCollection(value)) {
42
+ const correction = field === "tags" || field === "sources"
43
+ ? `Use an explicit ${field} add/remove/replace-all collection action.`
44
+ : "Use complete-document replacement: pull --doc-key <id>.md --out <file>, edit that file, then promote <file> --doc-key <id>.md --expected-version <version-from-pull>.";
45
+ throw new InvalidInputError(`Cannot assign '${field}': the old or new subtree contains a list. ${correction}`);
46
+ }
47
+ }
48
+ export function assertOrdinaryPatch(existing, proposed) {
49
+ for (const field of new Set([...Object.keys(existing), ...Object.keys(proposed)])) {
50
+ if (!okfValuesEqual(existing[field], proposed[field]))
51
+ assertNonCollectionAssignment(field, existing[field], proposed[field]);
52
+ }
53
+ }
54
+ function assertAssignmentName(field) {
55
+ if (managed.has(field))
56
+ throw new InvalidInputError(`'${field}' is managed metadata and cannot be assigned by a field action.`);
57
+ if (field === "tags" || field === "sources")
58
+ throw new InvalidInputError(`'${field}' requires an explicit collection add/remove/replace-all action.`);
59
+ }
60
+ /** Semantic legacy assignments retain input intent, including explicitly equal assignments. */
61
+ export function prepareDocumentAssignments(existing, assignments) {
62
+ if (!record(assignments))
63
+ throw new InvalidInputError("assignments must be a mapping");
64
+ for (const [field, value] of Object.entries(assignments)) {
65
+ assertAssignmentName(field);
66
+ assertNonCollectionAssignment(field, existing.frontmatter[field], value);
67
+ }
68
+ return { frontmatter: { ...existing.frontmatter, ...structuredClone(assignments) }, body: existing.body };
69
+ }
70
+ function sourceRow(value) {
71
+ if (!record(value) || typeof value.resource !== "string" || value.resource.trim() === "")
72
+ throw new InvalidInputError("A source entry requires a nonempty resource string.");
73
+ if (has(value, "id") && typeof value.id !== "string")
74
+ throw new InvalidInputError("A supplied source ID must be a string.");
75
+ }
76
+ function selectorIndex(rows, selector, edit) {
77
+ if (!record(selector) || Object.keys(selector).length !== 1 || !(has(selector, "id") || has(selector, "resource")))
78
+ throw new InvalidInputError("Select one source by exactly one id or resource.");
79
+ const key = has(selector, "id") ? "id" : "resource";
80
+ const value = selector[key];
81
+ // An imported empty ID is still an existing ID; it may be selected exactly but is never minted.
82
+ if (typeof value !== "string" || (key === "resource" && value.trim() === ""))
83
+ throw new InvalidInputError(`Source ${key} selector must be a string.`);
84
+ const matches = rows.flatMap((row, index) => record(row) && has(row, key) && row[key] === value ? [index] : []);
85
+ if (matches.length > 1)
86
+ throw new FieldActionError(`Source selector is ambiguous (${matches.length} matches); inspect sources and use a unique ID or version-guarded replace-all.`, {
87
+ reason: "ambiguous-source", field: "sources", selector: structuredClone(selector), ...sourceCandidates(matches.map(index => rows[index])),
88
+ });
89
+ if (matches.length === 0) {
90
+ if (edit)
91
+ throw new FieldActionError(`Source ${key} '${value}' was not found.`, {
92
+ reason: "source-not-found", field: "sources", selector: structuredClone(selector), ...sourceCandidates([]),
93
+ });
94
+ return -1;
95
+ }
96
+ const index = matches[0];
97
+ if (key === "resource" && has(rows[index], "id")) {
98
+ const id = rows[index].id;
99
+ if (typeof id !== "string")
100
+ throw new FieldActionError("This source has a malformed ID; repair it with version-guarded replace-all.", {
101
+ reason: "invalid-source-id", field: "sources", selector: structuredClone(selector), ...sourceCandidates([rows[index]]),
102
+ });
103
+ throw new FieldActionError(`This resource has source ID '${id}'; select it with --id.`, {
104
+ reason: "source-has-id", field: "sources", selector: structuredClone(selector), recommendedSelector: { id }, ...sourceCandidates([rows[index]]),
105
+ });
106
+ }
107
+ return index;
108
+ }
109
+ export function prepareDocumentFieldAction(existing, action, context) {
110
+ if (!record(action) || typeof action.field !== "string")
111
+ throw new InvalidInputError("A field action requires a field name.");
112
+ if (action.action === "set")
113
+ assertAssignmentName(action.field);
114
+ const keys = action.action === "edit" ? ["action", "field", "selector", "patch"]
115
+ : action.action === "remove" && action.field === "sources" ? ["action", "field", "selector"]
116
+ : ["action", "field", "value"];
117
+ if (Object.keys(action).some(key => !keys.includes(key)) || keys.some(key => !has(action, key)))
118
+ throw new InvalidInputError("Field action has missing or incompatible input properties.");
119
+ if ("value" in action && action.value === undefined)
120
+ throw new InvalidInputError("A field action value must be supplied; removing a field is not supported.");
121
+ let storageField = action.field;
122
+ let candidate = { frontmatter: structuredClone(existing.frontmatter), body: existing.body };
123
+ const scope = { field: action.field, action: action.action, outcome: "unchanged" };
124
+ if (action.action === "set") {
125
+ const kind = context.registry.kinds.get(String(existing.frontmatter.type));
126
+ const coordinate = kind && resolveKindFieldCoordinate(context.okfVersion, kind, action.field);
127
+ if (context.okfVersion === "0.1" && (action.field === "stale_after" || action.field === "usage_window"))
128
+ throw new InvalidInputError(`'${action.field}' requires OKF v0.2.`);
129
+ if (!isStandardDocumentSetField(action.field, context.okfVersion) && !coordinate) {
130
+ const supportedFields = [...new Set([
131
+ ...standard,
132
+ ...(context.okfVersion === "0.2" ? v02 : []),
133
+ ...(kind ? kindInputFieldNames(context.okfVersion, kind) : []),
134
+ ])].filter(field => {
135
+ if (managed.has(field) || field === "tags" || field === "sources")
136
+ return false;
137
+ if (context.okfVersion === "0.1" && (field === "stale_after" || field === "usage_window"))
138
+ return false;
139
+ const storage = kind && resolveKindFieldCoordinate(context.okfVersion, kind, field);
140
+ return !containsCollection(existing.frontmatter[storage?.storageField ?? field]);
141
+ }).sort();
142
+ throw new FieldActionError(`Unsupported set field '${action.field}'; supported fields: ${supportedFields.join(", ")}.`, {
143
+ reason: "unsupported-set-field", field: action.field, supportedFields,
144
+ });
145
+ }
146
+ storageField = coordinate?.storageField ?? action.field;
147
+ candidate = prepareDocumentAssignments(existing, { [storageField]: action.value });
148
+ if (!okfValuesEqual(existing.frontmatter[storageField], action.value))
149
+ scope.outcome = "edited";
150
+ if (scope.outcome !== "unchanged" && context.okfVersion === "0.1")
151
+ candidate.frontmatter.timestamp = (context.now ?? (() => new Date().toISOString()))();
152
+ return { candidate, scope, storageField };
153
+ }
154
+ if (action.field !== "tags" && action.field !== "sources")
155
+ throw new InvalidInputError("Collection actions support only tags and sources.");
156
+ if (!["add", "remove", "edit", "replace-all"].includes(action.action))
157
+ throw new InvalidInputError("Unknown field action.");
158
+ if (action.field === "sources" && context.okfVersion !== "0.2")
159
+ throw new InvalidInputError("sources actions require OKF v0.2.");
160
+ const previous = existing.frontmatter[action.field];
161
+ let rows;
162
+ if (action.action === "replace-all") {
163
+ if (!Array.isArray(action.value))
164
+ throw new InvalidInputError("replace-all requires a complete list (including [] to empty it).");
165
+ // Authored-value validation owns row compatibility; replacement permits deliberate duplicates.
166
+ rows = structuredClone(action.value);
167
+ if (action.field === "tags" && rows.some(value => typeof value !== "string"))
168
+ throw new InvalidInputError("tags must be a list of strings.");
169
+ scope.outcome = okfValuesEqual(previous, rows) ? "unchanged" : "replaced";
170
+ }
171
+ else {
172
+ if (previous !== undefined && !Array.isArray(previous))
173
+ throw new InvalidInputError(`'${action.field}' is not a list; repair it with version-guarded replace-all.`);
174
+ rows = structuredClone(previous ?? []);
175
+ if (action.field === "tags") {
176
+ if (action.action === "edit")
177
+ throw new InvalidInputError("tags supports add/remove/replace-all, not edit.");
178
+ if (typeof action.value !== "string")
179
+ throw new InvalidInputError("A tag must be a string.");
180
+ if (action.action === "add" && !rows.includes(action.value)) {
181
+ rows.push(action.value);
182
+ scope.outcome = "added";
183
+ }
184
+ if (action.action === "remove" && rows.includes(action.value)) {
185
+ rows = rows.filter(row => row !== action.value);
186
+ scope.outcome = "removed";
187
+ }
188
+ }
189
+ else if (action.action === "add") {
190
+ sourceRow(action.value);
191
+ if (has(action.value, "id")) {
192
+ const matches = rows.filter(row => record(row) && row.id === action.value.id);
193
+ if (matches.length > 1)
194
+ throw new FieldActionError("Source ID is ambiguous; repair duplicate IDs with replace-all.", {
195
+ reason: "ambiguous-source", field: "sources", selector: { id: action.value.id }, ...sourceCandidates(matches),
196
+ });
197
+ if (matches.length === 1 && !okfValuesEqual(matches[0], action.value))
198
+ throw new FieldActionError("Source ID conflicts with an existing entry; use edit with its observed version.", {
199
+ reason: "source-id-conflict", field: "sources", selector: { id: action.value.id }, recommendedSelector: { id: action.value.id }, ...sourceCandidates(matches),
200
+ });
201
+ }
202
+ if (!rows.some(row => okfValuesEqual(row, action.value))) {
203
+ rows.push(structuredClone(action.value));
204
+ scope.outcome = "added";
205
+ }
206
+ if (action.value.id !== undefined)
207
+ scope.affectedSourceIds = [action.value.id];
208
+ }
209
+ else {
210
+ const index = selectorIndex(rows, action.selector, action.action === "edit");
211
+ scope.selector = structuredClone(action.selector);
212
+ if (index >= 0) {
213
+ const old = rows[index];
214
+ if (typeof old.id === "string")
215
+ scope.affectedSourceIds = [old.id];
216
+ if (action.action === "remove") {
217
+ rows.splice(index, 1);
218
+ scope.outcome = "removed";
219
+ }
220
+ else {
221
+ if (!record(action.patch))
222
+ throw new InvalidInputError("A source edit requires a property mapping.");
223
+ for (const [property, value] of Object.entries(action.patch)) {
224
+ if (value === undefined)
225
+ throw new InvalidInputError("Source edit properties must have values.");
226
+ if (containsCollection(old[property]) || containsCollection(value))
227
+ throw new InvalidInputError(`Cannot assign source property '${property}': the old or new subtree contains a list. Use sources replace-all with an observed version.`);
228
+ }
229
+ if (has(action.patch, "id")) {
230
+ if (has(old, "id")) {
231
+ if (action.patch.id !== old.id)
232
+ throw new InvalidInputError("An existing source ID cannot change or be removed; use replace-all.");
233
+ }
234
+ else {
235
+ if (typeof action.patch.id !== "string" || action.patch.id.trim() === "")
236
+ throw new InvalidInputError("The first source ID must be a nonempty string.");
237
+ if (rows.some((row, i) => i !== index && record(row) && row.id === action.patch.id))
238
+ throw new InvalidInputError("The first source ID collides with an existing ID.");
239
+ scope.affectedSourceIds = [action.patch.id];
240
+ }
241
+ }
242
+ const next = { ...old, ...structuredClone(action.patch) };
243
+ if (!okfValuesEqual(old, next)) {
244
+ rows[index] = next;
245
+ scope.outcome = "edited";
246
+ }
247
+ }
248
+ }
249
+ }
250
+ }
251
+ // A missing collection removed from remains missing: a membership no-op writes no normalization.
252
+ if (scope.outcome !== "unchanged")
253
+ candidate.frontmatter[action.field] = rows;
254
+ if (action.field === "sources" && action.action === "replace-all") {
255
+ scope.affectedSourceIds = [...new Set([...(Array.isArray(previous) ? previous : []), ...rows].flatMap(row => record(row) && typeof row.id === "string" ? [row.id] : []))];
256
+ }
257
+ if (scope.outcome !== "unchanged" && context.okfVersion === "0.1")
258
+ candidate.frontmatter.timestamp = (context.now ?? (() => new Date().toISOString()))();
259
+ return { candidate, scope, storageField };
260
+ }
261
+ //# sourceMappingURL=document-field-actions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"document-field-actions.js","sourceRoot":"","sources":["../src/document-field-actions.ts"],"names":[],"mappings":"AAAA,+FAA+F;AAC/F,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAC1D,OAAO,EAAE,mBAAmB,EAAE,0BAA0B,EAAqB,MAAM,YAAY,CAAC;AAgBhG,4FAA4F;AAC5F,MAAM,OAAO,gBAAiB,SAAQ,iBAAiB;IAC5C,OAAO,CAA0B;IAC1C,YAAY,OAAe,EAAE,OAAgC;QAC3D,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,kBAAkB,CAAC;QAC/B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;CACF;AAwBD,MAAM,OAAO,GAAG,IAAI,GAAG,CAAC,CAAC,WAAW,EAAE,UAAU,EAAE,qBAAqB,EAAE,OAAO,EAAE,WAAW,CAAC,CAAC,CAAC;AAChG,MAAM,QAAQ,GAAG,IAAI,GAAG,CAAC,CAAC,OAAO,EAAE,aAAa,EAAE,MAAM,EAAE,UAAU,CAAC,CAAC,CAAC;AACvE,MAAM,GAAG,GAAG,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AAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;IAC5K,CAAC;IACD,IAAI,KAAK,CAAC,OAAO,KAAK,WAAW,IAAI,OAAO,CAAC,UAAU,KAAK,KAAK;QAAE,SAAS,CAAC,WAAW,CAAC,SAAS,GAAG,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC,CAAC,EAAE,CAAC;IACzJ,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,YAAY,EAAE,CAAC;AAC5C,CAAC"}
@@ -7,12 +7,17 @@
7
7
  * Consumers own their transport and presentation errors; this module throws typed
8
8
  * core failures and never imports CLI or browser concerns.
9
9
  */
10
+ import { type FieldAction, type FieldActionScope } from "./document-field-actions.js";
11
+ import { type KindFieldMutation } from "./kind-field-mutation.js";
12
+ import { type AppendVerificationOptions } from "./verification.js";
10
13
  import { InvalidInputError } from "./errors.js";
11
14
  import type { FieldPrecondition } from "./document-precondition.js";
12
15
  import type { KindRegistry } from "./kinds.js";
13
16
  import type { ValidationWarning } from "./content-type.js";
14
17
  import type { Bundle, ConceptId, Frontmatter, OkfDocument, Version } from "./types.js";
15
- export type DocumentMutationMode = "create-only" | "overwrite" | "patch";
18
+ /** replace-document shares patch CAS and metadata preparation, but permits an explicit
19
+ * whole-document replacement instead of ordinary assignment/list protection. */
20
+ export type DocumentMutationMode = "create-only" | "overwrite" | "patch" | "replace-document";
16
21
  /** The frontmatter and body a caller wants persisted; the service supplies the id. */
17
22
  export interface DocumentMutationCandidate {
18
23
  frontmatter: Frontmatter;
@@ -35,6 +40,21 @@ export declare class DocumentNotFoundError extends Error {
35
40
  readonly id: ConceptId;
36
41
  constructor(id: ConceptId);
37
42
  }
43
+ export type DocumentMutationInput = {
44
+ kind: "field-action";
45
+ action: FieldAction;
46
+ } | {
47
+ kind: "assign";
48
+ assignments: Record<string, unknown>;
49
+ body?: string;
50
+ refreshTimestamp?: boolean;
51
+ } | {
52
+ kind: "verify";
53
+ event: AppendVerificationOptions;
54
+ } | {
55
+ kind: "kind-field";
56
+ mutation: KindFieldMutation;
57
+ };
38
58
  export interface MutateDocumentOptions {
39
59
  bundle: Bundle;
40
60
  id: ConceptId;
@@ -44,7 +64,11 @@ export interface MutateDocumentOptions {
44
64
  /** Reject rather than return a non-empty kind warning set. */
45
65
  strict: boolean;
46
66
  /** Recomputed against a detached copy of every fresh CAS attempt. */
47
- buildCandidate: (existing: OkfDocument | undefined, context: DocumentMutationContext) => DocumentMutationCandidate | Promise<DocumentMutationCandidate>;
67
+ buildCandidate?: (existing: OkfDocument | undefined, context: DocumentMutationContext) => DocumentMutationCandidate | Promise<DocumentMutationCandidate>;
68
+ /** Actual semantic intent, evaluated on each fresh read. Mutually exclusive with buildCandidate. */
69
+ input?: DocumentMutationInput | ((existing: OkfDocument, context: DocumentMutationContext) => DocumentMutationInput | Promise<DocumentMutationInput>);
70
+ /** Adapter invariants observe every fresh candidate, regardless of input route. */
71
+ assertCandidate?: (existing: OkfDocument | undefined, candidate: DocumentMutationCandidate, context: DocumentMutationContext) => void | Promise<void>;
48
72
  /** Patch only: require an existing target or allow an expect-absent create. */
49
73
  onAbsent?: "fail" | "create";
50
74
  /** Retry budget for overwrite and ordinary patch. */
@@ -78,10 +102,30 @@ export interface MutateDocumentOptions {
78
102
  seedGenerationClock?: boolean;
79
103
  }
80
104
  export interface DocumentMutationResult {
105
+ scope?: FieldActionScope;
81
106
  doc: OkfDocument;
82
107
  changed: boolean;
83
108
  version: Version;
84
109
  warnings: ValidationWarning[];
85
110
  }
111
+ export interface PrepareDocumentMutationOptions {
112
+ id: ConceptId;
113
+ registry: KindRegistry;
114
+ strict: boolean;
115
+ okfVersion: "0.1" | "0.2";
116
+ now?: () => string;
117
+ actor?: string;
118
+ /** Content producer for generated.by; defaults to actor when omitted. */
119
+ producer?: string;
120
+ persistActor?: boolean;
121
+ compareTimestamp?: boolean;
122
+ seedGenerationClock?: boolean;
123
+ }
124
+ /** The pure patch preparation shared by mutation commits and governed previews. */
125
+ export declare function prepareDocumentMutationCandidate(existing: OkfDocument | undefined, rawCandidate: DocumentMutationCandidate, opts: PrepareDocumentMutationOptions): {
126
+ candidate: DocumentMutationCandidate;
127
+ changed: boolean;
128
+ warnings: ValidationWarning[];
129
+ };
86
130
  export declare function mutateDocument(opts: MutateDocumentOptions): Promise<DocumentMutationResult>;
87
131
  //# sourceMappingURL=document-mutation.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"document-mutation.d.ts","sourceRoot":"","sources":["../src/document-mutation.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAGH,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAmBhD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,4BAA4B,CAAC;AACpE,OAAO,KAAK,EAAE,YAAY,EAA4B,MAAM,YAAY,CAAC;AACzE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAC3D,OAAO,KAAK,EACV,MAAM,EACN,SAAS,EACT,WAAW,EACX,WAAW,EACX,OAAO,EACR,MAAM,YAAY,CAAC;AAIpB,MAAM,MAAM,oBAAoB,GAAG,aAAa,GAAG,WAAW,GAAG,OAAO,CAAC;AAEzE,sFAAsF;AACtF,MAAM,WAAW,yBAAyB;IACxC,WAAW,EAAE,WAAW,CAAC;IACzB,IAAI,EAAE,MAAM,CAAC;CACd;AAED,8FAA8F;AAC9F,MAAM,WAAW,uBAAuB;IACtC,UAAU,EAAE,KAAK,GAAG,KAAK,CAAC;CAC3B;AAED,4FAA4F;AAC5F,qBAAa,oBAAqB,SAAQ,iBAAiB;IACzD,QAAQ,CAAC,EAAE,EAAE,SAAS,CAAC;IACvB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,UAAU,EAAE,iBAAiB,EAAE,CAAC;IACzC,QAAQ,CAAC,UAAU,CAAC,EAAE,KAAK,GAAG,KAAK,CAA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AAC;IAC1B,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,yEAAyE;IACzE,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,mBAAmB,CAAC,EAAE,OAAO,CAAC;CAC/B;AAED,mFAAmF;AACnF,wBAAgB,gCAAgC,CAC9C,QAAQ,EAAE,WAAW,GAAG,SAAS,EACjC,YAAY,EAAE,yBAAyB,EACvC,IAAI,EAAE,8BAA8B,GACnC;IAAE,SAAS,EAAE,yBAAyB,CAAC;IAAC,OAAO,EAAE,OAAO,CAAC;IAAC,QAAQ,EAAE,iBAAiB,EAAE,CAAA;CAAE,CAY3F;AAiBD,wBAAsB,cAAc,CAAC,IAAI,EAAE,qBAAqB,GAAG,OAAO,CAAC,sBAAsB,CAAC,CA+NjG"}
@@ -7,6 +7,9 @@
7
7
  * Consumers own their transport and presentation errors; this module throws typed
8
8
  * core failures and never imports CLI or browser concerns.
9
9
  */
10
+ import { assertOrdinaryPatch, prepareDocumentAssignments, prepareDocumentFieldAction } from "./document-field-actions.js";
11
+ import { prepareKindFieldMutation } from "./kind-field-mutation.js";
12
+ import { appendVerificationEvent } from "./verification.js";
10
13
  import { okfValuesEqual } from "./okf-authored-values.js";
11
14
  import { InvalidInputError } from "./errors.js";
12
15
  import { assertAuthoredOkfStandardFields } from "./okf-standard-fields.js";
@@ -19,7 +22,7 @@ import { persistMutationActor, SUPERBEE_UPDATED_BY_FIELD } from "./mutation-attr
19
22
  import { defaultTimestampAndValidateAgainstRegistry, validateAgainstKind, } from "./kinds.js";
20
23
  import { versionedMutation } from "./mutation.js";
21
24
  import { VersionConflict } from "./versioning.js";
22
- import { readBundleOkfVersion, readDocVersioned, writeDocVersionedForEdition, } from "./bundle.js";
25
+ import { readBundleOkfVersion, readDocVersioned, writeDocVersionedForEdition, } from "./bundle-ops.js";
23
26
  const DEFAULT_MAX_ATTEMPTS = 5;
24
27
  /** Typed strict-kind rejection for trusted consumers to translate at their own boundary. */
25
28
  export class KindConformanceError extends InvalidInputError {
@@ -56,12 +59,12 @@ function withoutAutomaticMutationActor(frontmatter, okfVersion, kindRequiresActo
56
59
  const { actor: _actor, ...withoutActor } = rest;
57
60
  return withoutActor;
58
61
  }
59
- function withCanonicalComparableTimestamp(frontmatter) {
62
+ function withCanonicalComparableTimestamp(frontmatter, okfVersion) {
60
63
  const timestamp = frontmatter.timestamp;
61
64
  if (typeof timestamp !== "string")
62
65
  return frontmatter;
63
- const instant = Date.parse(timestamp);
64
- if (Number.isNaN(instant))
66
+ const instant = parseTimestamp(timestamp, okfVersion);
67
+ if (instant === null)
65
68
  return frontmatter;
66
69
  const canonical = new Date(instant).toISOString();
67
70
  return canonical === timestamp ? frontmatter : { ...frontmatter, timestamp: canonical };
@@ -78,10 +81,10 @@ function isNoopMutation(existing, candidate, compareTimestamp, okfVersion, ignor
78
81
  ? withoutAutomaticMutationActor(candidate.frontmatter, okfVersion, kindRequiresActor)
79
82
  : candidate.frontmatter;
80
83
  const existingFrontmatter = compareTimestamp
81
- ? withCanonicalComparableTimestamp(existingFrontmatterWithActorPolicy)
84
+ ? withCanonicalComparableTimestamp(existingFrontmatterWithActorPolicy, okfVersion)
82
85
  : existingFrontmatterWithActorPolicy;
83
86
  const candidateFrontmatter = compareTimestamp
84
- ? withCanonicalComparableTimestamp(candidateFrontmatterWithActorPolicy)
87
+ ? withCanonicalComparableTimestamp(candidateFrontmatterWithActorPolicy, okfVersion)
85
88
  : candidateFrontmatterWithActorPolicy;
86
89
  if (okfVersion === "0.2") {
87
90
  const withoutGeneratedAt = (frontmatter) => {
@@ -146,13 +149,15 @@ function withV02Metadata(candidate, existing, okfVersion, registry, now, seedGen
146
149
  allowGeneratedProvenanceSeed: seedGenerationClock,
147
150
  // Every v0.2 create gets one standard clock unless a usable time already exists (an explicit
148
151
  // legacy `timestamp`, a declared `generated.at`) or its kind requires `timestamp` (that one
149
- // clock is defaulted instead). Ungoverned types are the point: accumulation evidence for
152
+ // clock is defaulted instead when absent). Present unusable legacy values are preserved.
153
+ // Ungoverned types are the point: accumulation evidence for
150
154
  // per-bundle modeling (designs/agent-proposed-kind-conventions-v1) must not depend on a kind
151
155
  // already existing. Callers installing definitions opt out via `seedGenerationClock: false`.
152
156
  requireGenerationClock: existing === undefined
153
157
  && seedGenerationClock
154
- && !(kind?.fields.required.includes("timestamp") ?? false)
155
- && parseTimestamp(meaningfulChangeTimeValue(candidate.frontmatter)) === null,
158
+ && (!(kind?.fields.required.includes("timestamp") ?? false)
159
+ || Object.hasOwn(candidate.frontmatter, "timestamp"))
160
+ && parseTimestamp(meaningfulChangeTimeValue(candidate.frontmatter), okfVersion) === null,
156
161
  });
157
162
  }
158
163
  /** One stable instant per CAS decision, shared by every clock a bundle Kind explicitly carries. */
@@ -160,6 +165,17 @@ function onceNow(now) {
160
165
  let value;
161
166
  return () => (value ??= now());
162
167
  }
168
+ /** The pure patch preparation shared by mutation commits and governed previews. */
169
+ export function prepareDocumentMutationCandidate(existing, rawCandidate, opts) {
170
+ const decisionNow = onceNow(opts.now ?? (() => new Date().toISOString()));
171
+ const comparison = withV02Metadata(structuredClone(rawCandidate), existing, opts.okfVersion, opts.registry, decisionNow, opts.seedGenerationClock ?? true, opts.actor, opts.compareTimestamp ?? false, opts.producer);
172
+ if (existing && isNoopMutation(existing, comparison, opts.compareTimestamp ?? false, opts.okfVersion, opts.okfVersion === "0.2" && !!opts.persistActor && opts.actor !== undefined, opts.registry.kinds.get(String(comparison.frontmatter.type))?.fields.required.includes("actor") ?? false)) {
173
+ return { candidate: { frontmatter: structuredClone(existing.frontmatter), body: existing.body }, changed: false, warnings: [] };
174
+ }
175
+ const candidate = attributeCandidate(comparison, opts.actor, opts.persistActor ?? false, opts.okfVersion, opts.registry);
176
+ const { warnings } = validateCandidate(opts.id, candidate, opts.registry, opts.strict, opts.okfVersion, decisionNow, existing);
177
+ return { candidate, changed: true, warnings };
178
+ }
163
179
  /**
164
180
  * True when `existing` already satisfies ITS OWN governing kind — the monotone ratchet's
165
181
  * precondition (probe: tasks/overwrite-ratchet-survey). Validates the RAW existing
@@ -187,6 +203,50 @@ export async function mutateDocument(opts) {
187
203
  }
188
204
  const now = opts.now ?? (() => new Date().toISOString());
189
205
  const context = { okfVersion };
206
+ if ((opts.input === undefined) === (opts.buildCandidate === undefined))
207
+ throw new InvalidInputError("Supply exactly one semantic input or buildCandidate.");
208
+ if (opts.input !== undefined && opts.mode !== "patch")
209
+ throw new InvalidInputError("Semantic field/domain input requires patch mode.");
210
+ let scope;
211
+ const build = async (existing, decisionNow) => {
212
+ scope = undefined;
213
+ let candidate;
214
+ if (opts.input !== undefined) {
215
+ if (!existing)
216
+ throw new DocumentNotFoundError(opts.id);
217
+ const input = typeof opts.input === "function" ? await opts.input(structuredClone(existing), context) : opts.input;
218
+ if (input.kind === "field-action") {
219
+ if ((input.action.action === "edit" || input.action.action === "replace-all") && opts.expectedVersion === undefined)
220
+ throw new InvalidInputError("edit and replace-all require expectedVersion from an observed document.");
221
+ const prepared = prepareDocumentFieldAction(existing, input.action, { registry: opts.registry, okfVersion, now: decisionNow });
222
+ candidate = prepared.candidate;
223
+ scope = prepared.scope;
224
+ }
225
+ else if (input.kind === "assign") {
226
+ candidate = prepareDocumentAssignments(existing, input.assignments);
227
+ if (input.body !== undefined)
228
+ candidate.body = input.body;
229
+ if (input.refreshTimestamp && okfVersion === "0.1")
230
+ candidate.frontmatter.timestamp = decisionNow();
231
+ }
232
+ else if (input.kind === "verify") {
233
+ if (okfVersion !== "0.2")
234
+ throw new InvalidInputError("Verification events require OKF v0.2.");
235
+ candidate = { frontmatter: appendVerificationEvent(existing.frontmatter, input.event), body: existing.body };
236
+ }
237
+ else if (input.kind === "kind-field")
238
+ candidate = prepareKindFieldMutation(existing, input.mutation, okfVersion);
239
+ else
240
+ throw new InvalidInputError("Unknown document mutation input.");
241
+ }
242
+ else {
243
+ candidate = await opts.buildCandidate(existing === undefined ? undefined : structuredClone(existing), context);
244
+ if (existing && opts.mode === "patch")
245
+ assertOrdinaryPatch(existing.frontmatter, candidate.frontmatter);
246
+ }
247
+ await opts.assertCandidate?.(existing === undefined ? undefined : structuredClone(existing), structuredClone(candidate), context);
248
+ return candidate;
249
+ };
190
250
  if (opts.mode === "create-only") {
191
251
  // Fail closed: create-only issues NO read — its CAS basis is expect-absent — so there is no
192
252
  // observed state to evaluate an assertion against. Accepting the option and silently not
@@ -196,7 +256,7 @@ export async function mutateDocument(opts) {
196
256
  + "(use mode 'patch' with onAbsent: 'create')");
197
257
  }
198
258
  const decisionNow = onceNow(now);
199
- const withMetadata = withV02Metadata(await opts.buildCandidate(undefined, context), undefined, okfVersion, opts.registry, decisionNow, seedClock, opts.actor, compareTimestamp, opts.producer);
259
+ const withMetadata = withV02Metadata(await build(undefined, decisionNow), undefined, okfVersion, opts.registry, decisionNow, seedClock, opts.actor, compareTimestamp, opts.producer);
200
260
  const candidate = attributeCandidate(withMetadata, opts.actor, persistActor, okfVersion, opts.registry);
201
261
  const { warnings } = validateCandidate(opts.id, candidate, opts.registry, opts.strict, okfVersion, decisionNow);
202
262
  const { doc, version } = await writeDocVersionedForEdition(opts.bundle, { id: opts.id, ...candidate }, okfVersion, {
@@ -232,7 +292,7 @@ export async function mutateDocument(opts) {
232
292
  decide: async (existing) => {
233
293
  const decisionNow = onceNow(now);
234
294
  assertFieldPreconditions(opts.id, existing?.frontmatter, opts.preconditions, lastReadVersion);
235
- const withMetadata = withV02Metadata(await opts.buildCandidate(existing === undefined ? undefined : structuredClone(existing), context), existing, okfVersion, opts.registry, decisionNow, seedClock, opts.actor, compareTimestamp, opts.producer);
295
+ const withMetadata = withV02Metadata(await build(existing, decisionNow), existing, okfVersion, opts.registry, decisionNow, seedClock, opts.actor, compareTimestamp, opts.producer);
236
296
  const candidate = attributeCandidate(withMetadata, opts.actor, persistActor, okfVersion, opts.registry);
237
297
  const validated = validateCandidate(opts.id, candidate, opts.registry, opts.strict, okfVersion, decisionNow, existing);
238
298
  warnings = validated.warnings;
@@ -287,13 +347,13 @@ export async function mutateDocument(opts) {
287
347
  if (hardCas && lastReadVersion !== opts.expectedVersion) {
288
348
  throw new VersionConflict(opts.id, opts.expectedVersion, lastReadVersion);
289
349
  }
290
- const rawCandidate = await opts.buildCandidate(existing === undefined ? undefined : structuredClone(existing), context);
291
- const candidateForComparison = withV02Metadata(rawCandidate, existing, okfVersion, opts.registry, decisionNow, seedClock, opts.actor, compareTimestamp, opts.producer);
292
- if (existing && isNoopMutation(existing, candidateForComparison, compareTimestamp, okfVersion, okfVersion === "0.2" && persistActor && opts.actor !== undefined, opts.registry.kinds.get(String(candidateForComparison.frontmatter.type))?.fields.required.includes("actor") ?? false)) {
350
+ const rawCandidate = await build(existing, decisionNow);
351
+ const { candidate, changed, warnings } = prepareDocumentMutationCandidate(existing, rawCandidate, {
352
+ id: opts.id, registry: opts.registry, strict: opts.strict, okfVersion, now: decisionNow,
353
+ actor: opts.actor, producer: opts.producer, persistActor, compareTimestamp, seedGenerationClock: seedClock,
354
+ });
355
+ if (!changed)
293
356
  return { action: "done", result: { doc: existing, warnings: [] } };
294
- }
295
- const candidate = attributeCandidate(candidateForComparison, opts.actor, persistActor, okfVersion, opts.registry);
296
- const { warnings } = validateCandidate(opts.id, candidate, opts.registry, opts.strict, okfVersion, decisionNow, existing);
297
357
  return { action: "write", next: { id: opts.id, ...candidate }, result: { warnings } };
298
358
  },
299
359
  write: async (next, expectedVersion) => {
@@ -307,7 +367,7 @@ export async function mutateDocument(opts) {
307
367
  maxAttempts: hardCas ? 1 : maxAttempts,
308
368
  });
309
369
  return outcome.wrote
310
- ? { doc: savedDoc, changed: true, version: outcome.version, warnings: outcome.result.warnings }
311
- : { doc: outcome.result.doc, changed: false, version: outcome.version, warnings: [] };
370
+ ? { doc: savedDoc, changed: true, version: outcome.version, warnings: outcome.result.warnings, ...(scope ? { scope } : {}) }
371
+ : { doc: outcome.result.doc, changed: false, version: outcome.version, warnings: [], ...(scope ? { scope } : {}) };
312
372
  }
313
373
  //# sourceMappingURL=document-mutation.js.map