@powerhousedao/shared 6.2.2-dev.6 → 6.2.2-dev.60

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 (109) hide show
  1. package/dist/clis/args/access-token.mjs +1 -1
  2. package/dist/clis/args/{common-dbsvksvf.mjs → common-CcYbXrBx.mjs} +7 -2
  3. package/dist/clis/args/common-CcYbXrBx.mjs.map +1 -0
  4. package/dist/clis/args/{common-C5n5ai5C.d.mts → common-jbDGxlex.d.mts} +7 -4
  5. package/dist/clis/args/{common-C5n5ai5C.d.mts.map → common-jbDGxlex.d.mts.map} +1 -1
  6. package/dist/clis/args/common.d.mts +2 -2
  7. package/dist/clis/args/common.mjs +2 -2
  8. package/dist/clis/args/connect.d.mts +14 -5
  9. package/dist/clis/args/connect.d.mts.map +1 -1
  10. package/dist/clis/args/connect.mjs +2 -1
  11. package/dist/clis/args/connect.mjs.map +1 -1
  12. package/dist/clis/args/{generate-Cs5okckF.mjs → generate-CQ78RxVS.mjs} +2 -2
  13. package/dist/clis/args/{generate-Cs5okckF.mjs.map → generate-CQ78RxVS.mjs.map} +1 -1
  14. package/dist/clis/args/generate.mjs +1 -1
  15. package/dist/clis/args/{help-BkF9Cxud.mjs → help-Dk-d57W1.mjs} +3 -3
  16. package/dist/clis/args/{help-BkF9Cxud.mjs.map → help-Dk-d57W1.mjs.map} +1 -1
  17. package/dist/clis/args/help.mjs +1 -1
  18. package/dist/clis/args/index.d.mts +3 -3
  19. package/dist/clis/args/index.mjs +4 -4
  20. package/dist/clis/args/init.mjs +1 -1
  21. package/dist/clis/args/inspect.mjs +1 -1
  22. package/dist/clis/args/install.mjs +1 -1
  23. package/dist/clis/args/list.mjs +1 -1
  24. package/dist/clis/args/login.mjs +1 -1
  25. package/dist/clis/args/migrate.mjs +1 -1
  26. package/dist/clis/args/publish.mjs +1 -1
  27. package/dist/clis/args/registry.mjs +1 -1
  28. package/dist/clis/args/{service-51afW_Hz.d.mts → service-C88bN_g_.d.mts} +2 -2
  29. package/dist/clis/args/{service-51afW_Hz.d.mts.map → service-C88bN_g_.d.mts.map} +1 -1
  30. package/dist/clis/args/service.d.mts +1 -1
  31. package/dist/clis/args/service.mjs +1 -1
  32. package/dist/clis/args/switchboard.mjs +1 -1
  33. package/dist/clis/args/uninstall.mjs +1 -1
  34. package/dist/clis/args/unpublish.mjs +1 -1
  35. package/dist/clis/args/vetra.d.mts +1 -1
  36. package/dist/clis/args/vetra.mjs +1 -1
  37. package/dist/clis/build-config.d.mts +1 -1
  38. package/dist/clis/build-config.d.mts.map +1 -1
  39. package/dist/clis/constants.d.mts +177 -50
  40. package/dist/clis/constants.d.mts.map +1 -1
  41. package/dist/clis/constants.mjs +6 -2
  42. package/dist/clis/constants.mjs.map +1 -1
  43. package/dist/clis/index.d.mts +505 -13
  44. package/dist/clis/index.d.mts.map +1 -1
  45. package/dist/clis/index.mjs +310 -3
  46. package/dist/clis/index.mjs.map +1 -1
  47. package/dist/{config-loader-19K8n4DO.js → config-loader-Dw3syw7r.js} +10 -14
  48. package/dist/config-loader-Dw3syw7r.js.map +1 -0
  49. package/dist/connect/config-loader.d.ts +2 -1
  50. package/dist/connect/config-loader.d.ts.map +1 -1
  51. package/dist/connect/config-loader.js +1 -1
  52. package/dist/connect/index.d.ts +435 -14
  53. package/dist/connect/index.d.ts.map +1 -1
  54. package/dist/connect/index.js +498 -2
  55. package/dist/connect/index.js.map +1 -1
  56. package/dist/connect/json-adapter.d.ts.map +1 -1
  57. package/dist/{constants-C_EQX4DY.d.ts → constants-BP_gjn8g.d.ts} +1 -1
  58. package/dist/constants-BP_gjn8g.d.ts.map +1 -0
  59. package/dist/constants.d.ts +1 -1
  60. package/dist/document-drive/index.d.ts +2 -2
  61. package/dist/document-drive/index.d.ts.map +1 -1
  62. package/dist/document-model/index.d.ts +5 -5
  63. package/dist/document-model/index.js +1275 -130
  64. package/dist/document-model/index.js.map +1 -1
  65. package/dist/document-model/mock.d.ts +1 -1
  66. package/dist/document-model/mock.js +32 -3
  67. package/dist/document-model/mock.js.map +1 -1
  68. package/dist/document-model/utils.d.ts +2 -2
  69. package/dist/document-model/utils.js +1 -1
  70. package/dist/{index-CQDIrK1k.d.ts → index-BJU79_T5.d.ts} +1 -1
  71. package/dist/index-BJU79_T5.d.ts.map +1 -0
  72. package/dist/index-cFMRqBkg.d.ts +814 -0
  73. package/dist/index-cFMRqBkg.d.ts.map +1 -0
  74. package/dist/index.d.ts +5 -6
  75. package/dist/mock-BcFWPQyK.d.ts +22 -0
  76. package/dist/mock-BcFWPQyK.d.ts.map +1 -0
  77. package/dist/processors/index.d.ts +1 -1
  78. package/dist/registry/index.d.ts +5 -4
  79. package/dist/registry/index.d.ts.map +1 -1
  80. package/dist/registry/index.js +5 -4
  81. package/dist/registry/index.js.map +1 -1
  82. package/dist/registry/manifest-slim.d.ts +1 -1
  83. package/dist/registry/manifest-slim.d.ts.map +1 -1
  84. package/dist/registry/urls.d.ts +11 -0
  85. package/dist/registry/urls.d.ts.map +1 -0
  86. package/dist/registry/urls.js +15 -0
  87. package/dist/registry/urls.js.map +1 -0
  88. package/dist/{types-DvWPqxJr.d.ts → types-BYjTIoUq.d.ts} +29 -3
  89. package/dist/{types-DvWPqxJr.d.ts.map → types-BYjTIoUq.d.ts.map} +1 -1
  90. package/dist/{types-DXsYu6Tq.d.ts → types-CWwCnZQ_.d.ts} +458 -12
  91. package/dist/types-CWwCnZQ_.d.ts.map +1 -0
  92. package/dist/{utils-BEByNOHo.d.ts → utils-1EXU6Qr1.d.ts} +1 -1
  93. package/dist/utils-1EXU6Qr1.d.ts.map +1 -0
  94. package/dist/{utils-DKOFCM0Q.js → utils-CTt1XRn-.js} +36 -2
  95. package/dist/utils-CTt1XRn-.js.map +1 -0
  96. package/package.json +1 -1
  97. package/dist/clis/args/common-dbsvksvf.mjs.map +0 -1
  98. package/dist/config-loader-19K8n4DO.js.map +0 -1
  99. package/dist/constants-C_EQX4DY.d.ts.map +0 -1
  100. package/dist/index-CQDIrK1k.d.ts.map +0 -1
  101. package/dist/index-Dz7JrBXs.d.ts +0 -399
  102. package/dist/index-Dz7JrBXs.d.ts.map +0 -1
  103. package/dist/mock-CBcf78ra.d.ts +0 -7
  104. package/dist/mock-CBcf78ra.d.ts.map +0 -1
  105. package/dist/types-D0NNBVGA.d.ts +0 -167
  106. package/dist/types-D0NNBVGA.d.ts.map +0 -1
  107. package/dist/types-DXsYu6Tq.d.ts.map +0 -1
  108. package/dist/utils-BEByNOHo.d.ts.map +0 -1
  109. package/dist/utils-DKOFCM0Q.js.map +0 -1
@@ -1,10 +1,84 @@
1
- import { a as buildOperationSignatureParams, c as hex2ab, i as buildOperationSignatureMessage, n as generateId, o as getUnixTimestamp, r as ab2hex, s as hashBrowser, t as deriveOperationId } from "../utils-DKOFCM0Q.js";
1
+ import { a as base64UrlToBytes, c as getUnixTimestamp, i as base58Decode, l as hashBrowser, n as generateId, o as buildOperationSignatureMessage, r as ab2hex, s as buildOperationSignatureParams, t as deriveOperationId, u as hex2ab } from "../utils-CTt1XRn-.js";
2
2
  import { generateMock } from "./mock.js";
3
3
  import { ZodError, z } from "zod";
4
4
  import { stringify } from "safe-stable-stringify";
5
5
  import { strFromU8, strToU8, unzip, zip } from "fflate";
6
6
  import { castDraft, create, unsafe } from "mutative";
7
7
  import { constantCase, pascalCase } from "change-case";
8
+ //#region document-model/signatures.ts
9
+ /**
10
+ * What separates a signature's params when it travels as one string.
11
+ *
12
+ * GraphQL declares `signatures` as a list of strings, not a list of lists, so a
13
+ * tuple is joined for transport and split on arrival. The separator is here so
14
+ * the two halves cannot disagree about it - they live in different packages, and
15
+ * a mismatch would corrupt every signature that crossed the wire rather than
16
+ * failing outright.
17
+ */
18
+ const SIGNATURE_PARAM_SEPARATOR = ", ";
19
+ /** The number of params a signature carries. */
20
+ const SIGNATURE_PARAM_COUNT = 5;
21
+ /** Joins a signature's params for transport. Already-joined input passes through. */
22
+ function serializeSignature(signature) {
23
+ return Array.isArray(signature) ? signature.join(SIGNATURE_PARAM_SEPARATOR) : signature;
24
+ }
25
+ /**
26
+ * Splits a transported signature back into its params. A tuple passes through.
27
+ *
28
+ * Short input is padded rather than refused: verification reads the params by
29
+ * position and fails on a wrong one, which says more than a length complaint
30
+ * raised here would.
31
+ */
32
+ function deserializeSignature(signature) {
33
+ if (Array.isArray(signature)) return signature;
34
+ const parts = signature.split(SIGNATURE_PARAM_SEPARATOR);
35
+ return Array.from({ length: SIGNATURE_PARAM_COUNT }, (_unused, index) => parts[index] ?? "");
36
+ }
37
+ //#endregion
38
+ //#region document-model/action-transport.ts
39
+ /**
40
+ * Projects an action onto the fields the GraphQL `ActionInput` declares.
41
+ *
42
+ * A projection rather than a spread, because an input object rejects a field it
43
+ * does not declare, and that refusal takes the whole request with it. An action
44
+ * read back out of storage can carry fields the type no longer has - a legacy
45
+ * `attachments` array, or the operation fields left behind by a signing helper
46
+ * that returns an operation - and any one of them would sink an otherwise valid
47
+ * submission.
48
+ *
49
+ * Only fields the action actually carries are emitted, so an unsigned action
50
+ * sends no context at all rather than a context full of nulls.
51
+ */
52
+ function toTransportAction(action) {
53
+ if (action.input === void 0 || action.input === null) throw new Error(`Action ${action.id} (${action.type}) has no input, which the wire requires`);
54
+ const projected = {
55
+ id: action.id,
56
+ type: action.type,
57
+ timestampUtcMs: action.timestampUtcMs,
58
+ input: action.input,
59
+ scope: action.scope
60
+ };
61
+ const context = toTransportContext(action.context);
62
+ return context ? {
63
+ ...projected,
64
+ context
65
+ } : projected;
66
+ }
67
+ function toTransportContext(context) {
68
+ if (!context) return;
69
+ const projected = {};
70
+ if (context.prevOpIndex !== void 0) projected.prevOpIndex = context.prevOpIndex;
71
+ if (context.prevOpHash !== void 0) projected.prevOpHash = context.prevOpHash;
72
+ if (context.nonce !== void 0) projected.nonce = context.nonce;
73
+ const signer = context.signer;
74
+ if (signer) projected.signer = {
75
+ ...signer.user ? { user: signer.user } : {},
76
+ ...signer.app ? { app: signer.app } : {},
77
+ signatures: (signer.signatures ?? []).map(serializeSignature)
78
+ };
79
+ return Object.keys(projected).length > 0 ? projected : void 0;
80
+ }
81
+ //#endregion
8
82
  //#region document-model/errors.ts
9
83
  const FileSystemError = /* @__PURE__ */ new Error("File system not available.");
10
84
  var InvalidActionInputError = class extends Error {
@@ -39,6 +113,75 @@ var DowngradeNotSupportedError = class extends Error {
39
113
  this.toVersion = toVersion;
40
114
  }
41
115
  };
116
+ /**
117
+ * Thrown when INITIALIZE_AUTH is applied to an already-initialized auth scope.
118
+ * The genesis action is valid only at auth revision zero.
119
+ */
120
+ var AuthAlreadyInitializedError = class extends Error {
121
+ documentId;
122
+ constructor(documentId) {
123
+ super(`Auth scope already initialized for document ${documentId}: INITIALIZE_AUTH is valid only at auth revision zero`);
124
+ this.name = "AuthAlreadyInitializedError";
125
+ this.documentId = documentId;
126
+ }
127
+ };
128
+ /**
129
+ * Thrown when INITIALIZE_AUTH is not signed by the document creator (its signer
130
+ * does not match `header.sig.publicKey`), so it cannot set the auth policy.
131
+ */
132
+ var AuthInitializerNotCreatorError = class extends Error {
133
+ documentId;
134
+ constructor(documentId) {
135
+ super(`INITIALIZE_AUTH for document ${documentId} must be signed by the document creator`);
136
+ this.name = "AuthInitializerNotCreatorError";
137
+ this.documentId = documentId;
138
+ }
139
+ };
140
+ /**
141
+ * Thrown when INITIALIZE_AUTH carries a version below 1. Version 0 is reserved
142
+ * for the uninitialized auth scope.
143
+ */
144
+ var InvalidAuthVersionError = class extends Error {
145
+ documentId;
146
+ version;
147
+ constructor(documentId, version) {
148
+ super(`Invalid auth policy version ${version} for document ${documentId}: INITIALIZE_AUTH requires an integer version >= 1`);
149
+ this.name = "InvalidAuthVersionError";
150
+ this.documentId = documentId;
151
+ this.version = version;
152
+ }
153
+ };
154
+ /** Thrown when a duplicate would lose the source policy's version or creator binding. */
155
+ var AuthPolicyNotPreservedError = class extends Error {
156
+ documentId;
157
+ constructor(documentId) {
158
+ super(`Duplicating document ${documentId} would not preserve its auth policy: the copy loses the policy version or its creator binding`);
159
+ this.name = "AuthPolicyNotPreservedError";
160
+ this.documentId = documentId;
161
+ }
162
+ };
163
+ /**
164
+ * Thrown when a grant referenced by REMOVE_GRANT or MOVE_GRANT does not exist.
165
+ */
166
+ var GrantNotFoundError = class extends Error {
167
+ grantId;
168
+ constructor(grantId) {
169
+ super(`Grant not found in auth scope: ${grantId}`);
170
+ this.name = "GrantNotFoundError";
171
+ this.grantId = grantId;
172
+ }
173
+ };
174
+ /**
175
+ * Thrown when a disallowed action (UNDO, REDO, PRUNE) targets the auth scope.
176
+ */
177
+ var AuthActionNotAllowedError = class extends Error {
178
+ actionType;
179
+ constructor(actionType) {
180
+ super(`${actionType} is not permitted on the auth scope`);
181
+ this.name = "AuthActionNotAllowedError";
182
+ this.actionType = actionType;
183
+ }
184
+ };
42
185
  var HashMismatchError = class extends Error {
43
186
  _scope;
44
187
  _document;
@@ -65,6 +208,25 @@ var HashMismatchError = class extends Error {
65
208
  return this._operation;
66
209
  }
67
210
  };
211
+ /**
212
+ * Thrown when replay or import requires a document model version that is not
213
+ * registered. Carries the data the UI needs to explain the mismatch.
214
+ */
215
+ var UnsupportedDocumentModelVersionError = class extends Error {
216
+ documentType;
217
+ requiredVersion;
218
+ availableVersions;
219
+ constructor(documentType, requiredVersion, availableVersions) {
220
+ super(`No reducer registered for document version ${requiredVersion}. Available versions: ${availableVersions.join(", ")}`);
221
+ this.name = "UnsupportedDocumentModelVersionError";
222
+ this.documentType = documentType;
223
+ this.requiredVersion = requiredVersion;
224
+ this.availableVersions = availableVersions;
225
+ }
226
+ static isError(error) {
227
+ return Error.isError(error) && error.name === "UnsupportedDocumentModelVersionError";
228
+ }
229
+ };
68
230
  //#endregion
69
231
  //#region document-model/schemas.ts
70
232
  const isDefinedNonNullAny = (v) => v !== void 0 && v !== null;
@@ -553,6 +715,89 @@ const ConfigEntrySchema = z.object({
553
715
  required: z.boolean().optional(),
554
716
  default: z.boolean().optional()
555
717
  });
718
+ const PwaUrlPatternSchema = z.union([z.string(), z.strictObject({
719
+ source: z.string(),
720
+ flags: z.string().optional()
721
+ }).refine((p) => {
722
+ try {
723
+ new RegExp(p.source, p.flags);
724
+ return true;
725
+ } catch {
726
+ return false;
727
+ }
728
+ }, { message: "source/flags do not compile to a valid RegExp" })]);
729
+ const PwaRuntimeCachingSchema = z.strictObject({
730
+ urlPattern: PwaUrlPatternSchema,
731
+ handler: z.enum([
732
+ "CacheFirst",
733
+ "CacheOnly",
734
+ "NetworkFirst",
735
+ "NetworkOnly",
736
+ "StaleWhileRevalidate"
737
+ ]),
738
+ method: z.enum([
739
+ "GET",
740
+ "POST",
741
+ "PUT",
742
+ "DELETE",
743
+ "HEAD",
744
+ "PATCH"
745
+ ]).optional(),
746
+ options: z.strictObject({
747
+ cacheName: z.string().optional(),
748
+ networkTimeoutSeconds: z.number().optional(),
749
+ expiration: z.strictObject({
750
+ maxEntries: z.number().optional(),
751
+ maxAgeSeconds: z.number().optional()
752
+ }).optional(),
753
+ cacheableResponse: z.strictObject({
754
+ statuses: z.array(z.number()).optional(),
755
+ headers: z.record(z.string(), z.string()).optional()
756
+ }).optional()
757
+ }).optional()
758
+ });
759
+ const PwaIconSchema = z.strictObject({
760
+ src: z.string(),
761
+ sizes: z.string().optional(),
762
+ type: z.string().optional(),
763
+ purpose: z.string().optional()
764
+ });
765
+ const PwaFileHandlerSchema = z.strictObject({
766
+ accept: z.record(z.string(), z.array(z.string().regex(/^\./, "file extensions must start with '.'"))),
767
+ icons: z.array(PwaIconSchema).optional(),
768
+ launch_type: z.enum(["single-client", "multiple-clients"]).optional()
769
+ });
770
+ const PwaManifestOverrideSchema = z.strictObject({
771
+ name: z.string().optional(),
772
+ short_name: z.string().optional(),
773
+ description: z.string().optional(),
774
+ theme_color: z.string().optional(),
775
+ background_color: z.string().optional(),
776
+ display: z.enum([
777
+ "fullscreen",
778
+ "standalone",
779
+ "minimal-ui",
780
+ "browser"
781
+ ]).optional(),
782
+ start_url: z.string().optional(),
783
+ scope: z.string().optional(),
784
+ icons: z.array(PwaIconSchema).optional(),
785
+ file_handlers: z.array(PwaFileHandlerSchema).optional(),
786
+ launch_handler: z.strictObject({ client_mode: z.enum([
787
+ "auto",
788
+ "focus-existing",
789
+ "navigate-existing",
790
+ "navigate-new"
791
+ ]) }).optional()
792
+ });
793
+ const PwaConfigSchema = z.strictObject({
794
+ manifest: PwaManifestOverrideSchema.optional(),
795
+ globPatterns: z.array(z.string()).optional(),
796
+ globIgnores: z.array(z.string()).optional(),
797
+ maximumFileSizeToCacheInBytes: z.number().optional(),
798
+ runtimeCaching: z.array(PwaRuntimeCachingSchema).optional(),
799
+ navigateFallbackDenylist: z.array(PwaUrlPatternSchema).optional()
800
+ });
556
801
  const ManifestSchema = z.object({
557
802
  name: z.string(),
558
803
  description: z.string().optional(),
@@ -564,7 +809,8 @@ const ManifestSchema = z.object({
564
809
  editors: PowerhouseModulesSchema,
565
810
  processors: PowerhouseModulesSchema,
566
811
  subgraphs: PowerhouseModulesSchema,
567
- config: z.array(ConfigEntrySchema).optional()
812
+ config: z.array(ConfigEntrySchema).optional(),
813
+ pwa: PwaConfigSchema.optional()
568
814
  });
569
815
  //#endregion
570
816
  //#region document-model/actions.ts
@@ -850,6 +1096,542 @@ const actions = {
850
1096
  ...documentModelActions
851
1097
  };
852
1098
  //#endregion
1099
+ //#region document-model/document-type.ts
1100
+ const documentModelDocumentType = "powerhouse/document-model";
1101
+ const groupDocumentType = "powerhouse/reactor-group";
1102
+ /**
1103
+ * The group-model action types that change membership. The groups projection
1104
+ * filters its reads to these, so any other group operation is invisible to a
1105
+ * decision. Kept here so the reactor never depends on the group package; a
1106
+ * reactor-group test guards against drift.
1107
+ */
1108
+ const groupMembershipActionTypes = ["ADD_MEMBER", "REMOVE_MEMBER"];
1109
+ //#endregion
1110
+ //#region document-model/auth-v1.ts
1111
+ /** Maximum number of grants in a policy. */
1112
+ const MAX_AUTH_GRANTS = 100;
1113
+ /** Maximum nesting depth of a condition tree. */
1114
+ const MAX_CONDITION_DEPTH = 10;
1115
+ /** Maximum node count (conditions plus operands) of a condition tree. */
1116
+ const MAX_CONDITION_NODES = 100;
1117
+ /** Maximum entries in an execute capability's operation list. */
1118
+ const MAX_CAPABILITY_OPERATIONS = 100;
1119
+ /**
1120
+ * Thrown when a grant violates the v1 validation rules. The message is stored
1121
+ * on error operations, so it must be a pure function of the input.
1122
+ */
1123
+ var InvalidGrantError = class extends Error {
1124
+ grantId;
1125
+ constructor(grantId, problem) {
1126
+ super(`Invalid grant "${grantId}": ${problem}`);
1127
+ this.name = "InvalidGrantError";
1128
+ this.grantId = grantId;
1129
+ }
1130
+ };
1131
+ /** Thrown for a `{ group }` principal on a group document: references never chain. */
1132
+ var GroupPrincipalNotAllowedError = class extends Error {
1133
+ grantId;
1134
+ constructor(grantId) {
1135
+ super(`Grant "${grantId}" uses a group principal on a group document: a group's auth scope cannot reference other groups`);
1136
+ this.name = "GroupPrincipalNotAllowedError";
1137
+ this.grantId = grantId;
1138
+ }
1139
+ };
1140
+ /**
1141
+ * Thrown when a change would leave a creator-less policy with no grant
1142
+ * permitting execute on the auth scope. Without the creator carve-out no
1143
+ * subject could ever administer such a policy again.
1144
+ */
1145
+ var AuthAdministrationLockoutError = class extends Error {
1146
+ grantId;
1147
+ constructor(grantId) {
1148
+ super(`Change to grant "${grantId}" would leave no reachable grant permitting execute on the auth scope: a policy with no creator must always retain one`);
1149
+ this.name = "AuthAdministrationLockoutError";
1150
+ this.grantId = grantId;
1151
+ }
1152
+ };
1153
+ /**
1154
+ * Thrown when INITIALIZE_AUTH would create a creator-less policy with no grant
1155
+ * permitting execute on the auth scope. Such a policy would be born with no
1156
+ * subject able to administer it.
1157
+ */
1158
+ var AuthAdministrationMissingError = class extends Error {
1159
+ constructor() {
1160
+ super("Initial grants include no reachable grant permitting execute on the auth scope: a policy with no creator must always include one");
1161
+ this.name = "AuthAdministrationMissingError";
1162
+ }
1163
+ };
1164
+ const GRANT_KEYS = new Set([
1165
+ "id",
1166
+ "description",
1167
+ "effect",
1168
+ "principal",
1169
+ "capability",
1170
+ "where"
1171
+ ]);
1172
+ const PRINCIPAL_KINDS = new Set([
1173
+ "anyone",
1174
+ "address",
1175
+ "group",
1176
+ "match"
1177
+ ]);
1178
+ const COMPARISON_CONDITION_KINDS = new Set([
1179
+ "eq",
1180
+ "ne",
1181
+ "lt",
1182
+ "lte",
1183
+ "gt",
1184
+ "gte"
1185
+ ]);
1186
+ function isPlainValue(value) {
1187
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1188
+ }
1189
+ function operandProblem(value, capabilityScope, budget) {
1190
+ budget.nodes -= 1;
1191
+ if (budget.nodes < 0) return `condition exceeds 100 nodes`;
1192
+ if (!isPlainValue(value)) return "operand must be an object";
1193
+ const keys = Object.keys(value);
1194
+ if (keys.length !== 1) return "operand must have exactly one of attr or lit";
1195
+ if (keys[0] === "attr") {
1196
+ const attr = value.attr;
1197
+ if (typeof attr !== "string" || attr.length === 0) return "attr must be a non-empty string";
1198
+ if (capabilityScope !== void 0 && capabilityScope !== "*" && attr.startsWith("doc.")) {
1199
+ const pathScope = attr.split(".")[1] ?? "";
1200
+ if (pathScope !== capabilityScope) return `condition path "${attr}" reads scope "${pathScope}" but the capability covers only scope "${capabilityScope}"`;
1201
+ }
1202
+ return null;
1203
+ }
1204
+ if (keys[0] === "lit") {
1205
+ const lit = value.lit;
1206
+ if (lit !== null && typeof lit !== "string" && typeof lit !== "number" && typeof lit !== "boolean") return "lit must be a string, number, boolean, or null";
1207
+ if (typeof lit === "number" && !Number.isFinite(lit)) return "lit must be a finite number";
1208
+ if (typeof lit === "number" && Object.is(lit, -0)) return "lit must not be negative zero";
1209
+ return null;
1210
+ }
1211
+ return `unknown operand kind "${keys[0]}"`;
1212
+ }
1213
+ function conditionProblem(value, capabilityScope, depth, budget) {
1214
+ if (depth > 10) return `condition exceeds depth 10`;
1215
+ budget.nodes -= 1;
1216
+ if (budget.nodes < 0) return `condition exceeds 100 nodes`;
1217
+ if (!isPlainValue(value)) return "condition must be an object";
1218
+ const keys = Object.keys(value);
1219
+ if (keys.length !== 1) return "condition must have exactly one operator";
1220
+ const kind = keys[0];
1221
+ const body = value[kind];
1222
+ if (COMPARISON_CONDITION_KINDS.has(kind)) {
1223
+ if (!Array.isArray(body) || body.length !== 2) return `${kind} requires a pair of operands`;
1224
+ for (const operand of body) {
1225
+ const problem = operandProblem(operand, capabilityScope, budget);
1226
+ if (problem !== null) return problem;
1227
+ }
1228
+ return null;
1229
+ }
1230
+ if (kind === "in" || kind === "notIn") {
1231
+ if (!Array.isArray(body) || body.length !== 2 || !Array.isArray(body[1])) return `${kind} requires an operand and an operand list`;
1232
+ const first = operandProblem(body[0], capabilityScope, budget);
1233
+ if (first !== null) return first;
1234
+ for (const operand of body[1]) {
1235
+ const problem = operandProblem(operand, capabilityScope, budget);
1236
+ if (problem !== null) return problem;
1237
+ }
1238
+ return null;
1239
+ }
1240
+ if (kind === "exists") return operandProblem(body, capabilityScope, budget);
1241
+ if (kind === "and" || kind === "or") {
1242
+ if (!Array.isArray(body)) return `${kind} requires a condition list`;
1243
+ for (const child of body) {
1244
+ const problem = conditionProblem(child, capabilityScope, depth + 1, budget);
1245
+ if (problem !== null) return problem;
1246
+ }
1247
+ return null;
1248
+ }
1249
+ if (kind === "not") return conditionProblem(body, capabilityScope, depth + 1, budget);
1250
+ return `unknown condition operator "${kind}"`;
1251
+ }
1252
+ function principalProblem(value, capabilityScope) {
1253
+ if (!isPlainValue(value)) return "principal must be an object";
1254
+ const keys = Object.keys(value);
1255
+ if (keys.length !== 1 || !PRINCIPAL_KINDS.has(keys[0])) return "principal must have exactly one of anyone, address, group, or match";
1256
+ const kind = keys[0];
1257
+ if (kind === "anyone" && value.anyone !== true) return "anyone must be true";
1258
+ if (kind === "address") {
1259
+ const address = value.address;
1260
+ if (typeof address !== "string" || address.length === 0) return "address must be a non-empty string";
1261
+ }
1262
+ if (kind === "group") {
1263
+ const group = value.group;
1264
+ if (typeof group !== "string" || group.length === 0) return "group must be a non-empty string";
1265
+ }
1266
+ if (kind === "match") return conditionProblem(value.match, capabilityScope, 1, { nodes: 100 });
1267
+ return null;
1268
+ }
1269
+ function capabilityProblem(value) {
1270
+ if (!isPlainValue(value)) return "capability must be an object";
1271
+ const can = value.can;
1272
+ if (can !== "read" && can !== "execute") return "capability.can must be read or execute";
1273
+ const allowedKeys = can === "execute" ? [
1274
+ "can",
1275
+ "scope",
1276
+ "operation"
1277
+ ] : ["can", "scope"];
1278
+ const unknownKeys = Object.keys(value).filter((key) => !allowedKeys.includes(key)).sort();
1279
+ if (unknownKeys.length > 0) return `unknown capability key "${unknownKeys[0]}"`;
1280
+ if (value.scope !== void 0) {
1281
+ if (typeof value.scope !== "string" || value.scope.length === 0) return "capability.scope must be a non-empty string";
1282
+ }
1283
+ if (can === "execute" && value.operation !== void 0) {
1284
+ const operation = value.operation;
1285
+ if (!Array.isArray(operation)) return "capability.operation must be an array";
1286
+ if (operation.length > 100) return `capability.operation exceeds 100 entries`;
1287
+ for (const entry of operation) if (typeof entry !== "string" || entry.length === 0) return "capability.operation entries must be non-empty strings";
1288
+ }
1289
+ return null;
1290
+ }
1291
+ /** Returns the first v1-rule violation, or null. Pure, total, deterministic. */
1292
+ function grantProblem(value) {
1293
+ if (!isPlainValue(value)) return "grant must be an object";
1294
+ const unknownKeys = Object.keys(value).filter((key) => !GRANT_KEYS.has(key)).sort();
1295
+ if (unknownKeys.length > 0) return `unknown grant key "${unknownKeys[0]}"`;
1296
+ if (typeof value.id !== "string" || value.id.length === 0) return "id must be a non-empty string";
1297
+ if (typeof value.description !== "string") return "description must be a string";
1298
+ if (value.effect !== "allow" && value.effect !== "deny") return "effect must be allow or deny";
1299
+ const capabilityValue = value.capability;
1300
+ const capability = capabilityProblem(capabilityValue);
1301
+ if (capability !== null) return capability;
1302
+ const capabilityScope = capabilityValue.scope;
1303
+ const principal = principalProblem(value.principal, capabilityScope);
1304
+ if (principal !== null) return principal;
1305
+ if (value.where !== void 0) return conditionProblem(value.where, capabilityScope, 1, { nodes: 100 });
1306
+ return null;
1307
+ }
1308
+ const GrantSchema = () => z.custom((value) => grantProblem(value) === null);
1309
+ /** V1 shape rules plus the group-document group-principal ban. */
1310
+ function assertValidGrant(grant, documentType) {
1311
+ const grantId = isPlainValue(grant) && typeof grant.id === "string" ? grant.id : "";
1312
+ const problem = grantProblem(grant);
1313
+ if (problem !== null) throw new InvalidGrantError(grantId, problem);
1314
+ if (documentType === "powerhouse/reactor-group" && "group" in grant.principal) throw new GroupPrincipalNotAllowedError(grantId);
1315
+ }
1316
+ /**
1317
+ * Validates an initial grant list: the count cap, every grant, and — on a
1318
+ * creator-less policy — that some grant keeps the auth scope administrable.
1319
+ */
1320
+ function assertValidInitialGrants(grants, documentType, creator) {
1321
+ if (grants.length > 100) throw new InvalidGrantError("", `policy exceeds 100 grants`);
1322
+ for (const grant of grants) assertValidGrant(grant, documentType);
1323
+ if (creator === void 0 && !administrationReachable(grants)) throw new AuthAdministrationMissingError();
1324
+ }
1325
+ /**
1326
+ * Validates a grant upsert: the grant itself, the count cap on append, and
1327
+ * administration retention. Retention is checked on an append as well as an
1328
+ * in-place replace, because a grant appended after the administration grant can
1329
+ * shadow it (evaluation is last-applicable-grant-wins) and so take
1330
+ * administration away without removing anything.
1331
+ */
1332
+ function assertValidGrantUpsert(grant, existing, documentType, creator) {
1333
+ assertValidGrant(grant, documentType);
1334
+ const exists = existing.some((g) => g.id === grant.id);
1335
+ if (!exists && existing.length >= 100) throw new InvalidGrantError(grant.id, `policy exceeds 100 grants`);
1336
+ assertAuthAdministrationRetained(creator, existing, exists ? existing.map((g) => g.id === grant.id ? grant : g) : [...existing, grant], grant.id);
1337
+ }
1338
+ /**
1339
+ * The request whose coverage keeps a policy administrable: a subject who may
1340
+ * SET_GRANT can upsert any grant, so every other repair stays reachable.
1341
+ */
1342
+ const AUTH_ADMINISTRATION_REQUEST = {
1343
+ verb: "execute",
1344
+ scope: "auth",
1345
+ operation: "SET_GRANT"
1346
+ };
1347
+ /**
1348
+ * Whether some subject can still administer the auth scope under this grant list.
1349
+ *
1350
+ * Asks the evaluator rather than pattern-matching a single grant: evaluation is
1351
+ * last-applicable-grant-wins, so an allow that some later deny shadows keeps
1352
+ * nothing reachable even though it is still present in the list. Only anyone and
1353
+ * address principals are candidates, because those are the ones v1 can match at
1354
+ * all; a `where` condition or a group or match principal never applies.
1355
+ */
1356
+ function administrationReachable(grants) {
1357
+ return grants.some((grant) => {
1358
+ const subject = administrationCandidate(grant);
1359
+ if (subject === void 0) return false;
1360
+ return evaluateGrantStack(grants, subject, AUTH_ADMINISTRATION_REQUEST).decision === "allow";
1361
+ });
1362
+ }
1363
+ /**
1364
+ * The subject to test this grant with, or undefined when the grant could never
1365
+ * carry administration for anyone.
1366
+ */
1367
+ function administrationCandidate(grant) {
1368
+ if (grant.effect !== "allow" || grant.where !== void 0 || !capabilityCovers(grant.capability, AUTH_ADMINISTRATION_REQUEST)) return;
1369
+ if ("address" in grant.principal) return {
1370
+ address: grant.principal.address,
1371
+ key: void 0
1372
+ };
1373
+ if ("anyone" in grant.principal) return {
1374
+ address: void 0,
1375
+ key: void 0
1376
+ };
1377
+ }
1378
+ /**
1379
+ * A creator-less policy must always retain a grant permitting execute on the
1380
+ * auth scope; on a signed document the creator carve-out keeps administration
1381
+ * reachable instead. Rejects a change that takes the last such grant away. A
1382
+ * policy already without one is left alone: the change is not what locks it.
1383
+ */
1384
+ function assertAuthAdministrationRetained(creator, previous, next, grantId) {
1385
+ if (creator !== void 0) return;
1386
+ if (administrationReachable(previous) && !administrationReachable(next)) throw new AuthAdministrationLockoutError(grantId);
1387
+ }
1388
+ /**
1389
+ * An operand whose shape validation would have rejected. Distinguished from
1390
+ * an unresolved path so a structurally malformed operand poisons its whole
1391
+ * condition to false rather than reading as "absent", which `not` would
1392
+ * otherwise widen to true.
1393
+ */
1394
+ const INVALID_OPERAND = Symbol("invalid-operand");
1395
+ /**
1396
+ * Narrows to the values conditions compare. An object, array, or non-finite
1397
+ * number resolves to undefined, and every comparison involving undefined is
1398
+ * false.
1399
+ */
1400
+ function asConditionValue(value) {
1401
+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;
1402
+ if (typeof value === "number" && Number.isFinite(value)) return value;
1403
+ }
1404
+ /**
1405
+ * Resolves one operand. Attr roots: `subject.*`, `doc.<scope>.*` where the
1406
+ * scope must be the executing scope (validation already rejects any other,
1407
+ * but resolution stays total), and `action.input.*`. Path steps read own
1408
+ * properties only, so prototype members can never influence a verdict.
1409
+ */
1410
+ function resolveOperand(operand, subject, request, conditions) {
1411
+ if (!isPlainValue(operand)) return INVALID_OPERAND;
1412
+ const keys = Object.keys(operand);
1413
+ if (keys.length !== 1) return INVALID_OPERAND;
1414
+ if (keys[0] === "lit") {
1415
+ const value = asConditionValue(operand.lit);
1416
+ return value === void 0 ? INVALID_OPERAND : value;
1417
+ }
1418
+ if (keys[0] !== "attr") return INVALID_OPERAND;
1419
+ const attr = operand.attr;
1420
+ if (typeof attr !== "string" || attr.length === 0) return INVALID_OPERAND;
1421
+ const path = attr.split(".");
1422
+ let value;
1423
+ let rest;
1424
+ if (path[0] === "subject") {
1425
+ value = subject;
1426
+ rest = path.slice(1);
1427
+ } else if (path[0] === "doc") {
1428
+ if (path[1] !== request.scope) return;
1429
+ value = conditions.scopeState;
1430
+ rest = path.slice(2);
1431
+ } else if (path[0] === "action" && path[1] === "input") {
1432
+ value = conditions.actionInput;
1433
+ rest = path.slice(2);
1434
+ } else return;
1435
+ for (const segment of rest) {
1436
+ if (!isPlainValue(value) || !Object.hasOwn(value, segment)) return;
1437
+ value = value[segment];
1438
+ }
1439
+ return asConditionValue(value);
1440
+ }
1441
+ /**
1442
+ * Total order within one type: numbers numerically, strings by code point.
1443
+ * Everything else, including mixed types, does not order.
1444
+ */
1445
+ function compareValues(left, right) {
1446
+ if (typeof left === "number" && typeof right === "number") return left < right ? -1 : left > right ? 1 : 0;
1447
+ if (typeof left === "string" && typeof right === "string") {
1448
+ const leftPoints = Array.from(left);
1449
+ const rightPoints = Array.from(right);
1450
+ const shared = Math.min(leftPoints.length, rightPoints.length);
1451
+ for (let i = 0; i < shared; i++) {
1452
+ const a = leftPoints[i].codePointAt(0) ?? 0;
1453
+ const b = rightPoints[i].codePointAt(0) ?? 0;
1454
+ if (a !== b) return a < b ? -1 : 1;
1455
+ }
1456
+ return leftPoints.length === rightPoints.length ? 0 : leftPoints.length < rightPoints.length ? -1 : 1;
1457
+ }
1458
+ }
1459
+ /**
1460
+ * Tri-state evaluation: undefined marks a structurally invalid node, which
1461
+ * poisons the whole tree to false at the top — and a structurally malformed
1462
+ * operand poisons its condition the same way. Both are distinct from an
1463
+ * operand whose path fails to resolve, which is a valid comparison that is
1464
+ * false. The distinction keeps `not` from widening over malformed input.
1465
+ */
1466
+ function evaluateNode(node, subject, request, conditions) {
1467
+ if (!isPlainValue(node)) return;
1468
+ const keys = Object.keys(node);
1469
+ if (keys.length !== 1) return;
1470
+ const kind = keys[0];
1471
+ const body = node[kind];
1472
+ switch (kind) {
1473
+ case "eq":
1474
+ case "ne":
1475
+ case "lt":
1476
+ case "lte":
1477
+ case "gt":
1478
+ case "gte": {
1479
+ if (!Array.isArray(body) || body.length !== 2) return;
1480
+ const left = resolveOperand(body[0], subject, request, conditions);
1481
+ const right = resolveOperand(body[1], subject, request, conditions);
1482
+ if (left === INVALID_OPERAND || right === INVALID_OPERAND) return;
1483
+ if (left === void 0 || right === void 0) return false;
1484
+ if (kind === "eq") return left === right;
1485
+ if (kind === "ne") return left !== right;
1486
+ const order = compareValues(left, right);
1487
+ if (order === void 0) return false;
1488
+ switch (kind) {
1489
+ case "lt": return order < 0;
1490
+ case "lte": return order <= 0;
1491
+ case "gt": return order > 0;
1492
+ case "gte": return order >= 0;
1493
+ }
1494
+ return;
1495
+ }
1496
+ case "in":
1497
+ case "notIn": {
1498
+ if (!Array.isArray(body) || body.length !== 2 || !Array.isArray(body[1])) return;
1499
+ const left = resolveOperand(body[0], subject, request, conditions);
1500
+ if (left === INVALID_OPERAND) return;
1501
+ const elements = body[1].map((element) => resolveOperand(element, subject, request, conditions));
1502
+ if (elements.some((value) => value === INVALID_OPERAND)) return;
1503
+ if (left === void 0) return false;
1504
+ const found = elements.some((value) => value !== void 0 && value === left);
1505
+ return kind === "in" ? found : !found;
1506
+ }
1507
+ case "exists": {
1508
+ const value = resolveOperand(body, subject, request, conditions);
1509
+ if (value === INVALID_OPERAND) return;
1510
+ return value !== void 0;
1511
+ }
1512
+ case "and":
1513
+ case "or": {
1514
+ if (!Array.isArray(body)) return;
1515
+ let result = kind === "and";
1516
+ for (const child of body) {
1517
+ const value = evaluateNode(child, subject, request, conditions);
1518
+ if (value === void 0) return;
1519
+ if (kind === "and") result = result && value;
1520
+ else result = result || value;
1521
+ }
1522
+ return result;
1523
+ }
1524
+ case "not": {
1525
+ const value = evaluateNode(body, subject, request, conditions);
1526
+ return value === void 0 ? void 0 : !value;
1527
+ }
1528
+ default: return;
1529
+ }
1530
+ }
1531
+ /**
1532
+ * Evaluates a version-1 condition. Deterministic, total, and pure: any input
1533
+ * shape yields a boolean and never throws, and a malformed condition is
1534
+ * false. These are consensus semantics, versioned by `PHAuthState.version`;
1535
+ * changing them requires a new version.
1536
+ */
1537
+ function evaluateCondition(condition, subject, request, conditions) {
1538
+ return evaluateNode(condition, subject, request, conditions) === true;
1539
+ }
1540
+ /** Whether a capability's scope reaches the requested one. */
1541
+ function scopeCovers(scope, requested) {
1542
+ return scope === void 0 || scope === "*" || scope === requested;
1543
+ }
1544
+ /**
1545
+ * Whether one grant answers this request.
1546
+ *
1547
+ * A grant allowing execute on a scope also allows reading it: executing an
1548
+ * operation means reading the state it applies to, so permitting the write while
1549
+ * withholding the read would describe an access nobody could use. The converse
1550
+ * does not hold -- a read grant confers no write.
1551
+ *
1552
+ * Only an allow carries across. A deny on execute withholds the write and says
1553
+ * nothing about the read, so a policy locking writes down does not silently
1554
+ * revoke a read grant sitting before it. The operation list is not consulted
1555
+ * either: it restricts which operations may be executed, not whether the scope
1556
+ * is visible, and a read carries no operation to match against.
1557
+ *
1558
+ * Reads are not consensus -- no replica records a read, and the two read call
1559
+ * sites are both inside the read gate -- so this rule is not part of what makes
1560
+ * an operation valid, and does not need a policy version of its own.
1561
+ */
1562
+ function grantAnswers(grant, request) {
1563
+ if (capabilityCovers(grant.capability, request)) return true;
1564
+ return request.verb === "read" && grant.effect === "allow" && grant.capability.can === "execute" && scopeCovers(grant.capability.scope, request.scope);
1565
+ }
1566
+ function capabilityCovers(capability, request) {
1567
+ if (capability.can !== request.verb) return false;
1568
+ if (!scopeCovers(capability.scope, request.scope)) return false;
1569
+ if (capability.can === "execute") {
1570
+ if (capability.operation === void 0) return true;
1571
+ return request.operation !== void 0 && capability.operation.includes(request.operation);
1572
+ }
1573
+ return true;
1574
+ }
1575
+ function principalMatches(principal, subject, request, groups, conditions) {
1576
+ if ("anyone" in principal) return true;
1577
+ if ("address" in principal) return subject.address !== void 0 && subject.address.toLowerCase() === principal.address.toLowerCase();
1578
+ if ("group" in principal) {
1579
+ if (groups === void 0 || subject.address === void 0) return false;
1580
+ const group = groups[principal.group];
1581
+ if (group === void 0 || !Array.isArray(group.members)) return false;
1582
+ const address = subject.address.toLowerCase();
1583
+ return group.members.some((member) => member.toLowerCase() === address);
1584
+ }
1585
+ if ("match" in principal) {
1586
+ if (conditions === void 0) return false;
1587
+ return evaluateCondition(principal.match, subject, request, conditions);
1588
+ }
1589
+ return false;
1590
+ }
1591
+ /**
1592
+ * The group document ids named by `{ group }` principals in a grant list, in
1593
+ * order of first appearance. These are the streams the groups projection reads.
1594
+ */
1595
+ function referencedGroupIds(grants) {
1596
+ const ids = [];
1597
+ for (const grant of grants) if ("group" in grant.principal && !ids.includes(grant.principal.group)) ids.push(grant.principal.group);
1598
+ return ids;
1599
+ }
1600
+ /**
1601
+ * Evaluates a v1 grant stack: default deny, last applicable grant wins, and
1602
+ * reports which grant decided it. Group principals match only against a
1603
+ * supplied groups map, and `where` clauses and { match } principals evaluate
1604
+ * only against a supplied condition context; a grant that uses an unsupplied
1605
+ * feature never applies.
1606
+ */
1607
+ function evaluateGrantStack(grants, subject, request, groups, conditions) {
1608
+ let applicable;
1609
+ for (const grant of grants) {
1610
+ if (grant.where !== void 0) {
1611
+ if (conditions === void 0) continue;
1612
+ if (!evaluateCondition(grant.where, subject, request, conditions)) continue;
1613
+ }
1614
+ if (grantAnswers(grant, request) && principalMatches(grant.principal, subject, request, groups, conditions)) applicable = grant;
1615
+ }
1616
+ if (applicable === void 0) return {
1617
+ decision: "deny",
1618
+ refusal: "no-applicable-grant"
1619
+ };
1620
+ if (applicable.effect === "deny") return {
1621
+ decision: "deny",
1622
+ refusal: "denied-by-grant",
1623
+ grantId: applicable.id
1624
+ };
1625
+ return { decision: "allow" };
1626
+ }
1627
+ /**
1628
+ * Evaluates a v1 grant stack: default deny, last applicable grant wins. This is
1629
+ * {@link evaluateGrantStack} with the reason dropped.
1630
+ */
1631
+ function evaluateGrants(grants, subject, request, groups, conditions) {
1632
+ return evaluateGrantStack(grants, subject, request, groups, conditions).decision;
1633
+ }
1634
+ //#endregion
853
1635
  //#region document-model/constants.ts
854
1636
  const documentModelFileExtension = "phdm";
855
1637
  const documentModelInitialLocalState = {};
@@ -1436,8 +2218,403 @@ const HASH_ALGORITHM_SHA512 = "sha512";
1436
2218
  const HASH_ENCODING_BASE64 = "base64";
1437
2219
  const HASH_ENCODING_HEX = "hex";
1438
2220
  //#endregion
1439
- //#region document-model/document-type.ts
1440
- const documentModelDocumentType = "powerhouse/document-model";
2221
+ //#region document-model/state.ts
2222
+ /**
2223
+ * Creates a default PHAuthState
2224
+ */
2225
+ function defaultAuthState() {
2226
+ return {
2227
+ version: 0,
2228
+ grants: []
2229
+ };
2230
+ }
2231
+ /**
2232
+ * Creates a default PHDocumentState
2233
+ */
2234
+ function defaultDocumentState() {
2235
+ return {
2236
+ version: 0,
2237
+ hash: {
2238
+ algorithm: HASH_ALGORITHM_SHA1,
2239
+ encoding: HASH_ENCODING_BASE64
2240
+ }
2241
+ };
2242
+ }
2243
+ /**
2244
+ * Creates a default PHBaseState with auth and document properties
2245
+ */
2246
+ function defaultBaseState() {
2247
+ return {
2248
+ auth: defaultAuthState(),
2249
+ document: defaultDocumentState()
2250
+ };
2251
+ }
2252
+ /**
2253
+ * Creates a PHAuthState with the given properties
2254
+ */
2255
+ function createAuthState(auth) {
2256
+ return {
2257
+ ...defaultAuthState(),
2258
+ ...auth
2259
+ };
2260
+ }
2261
+ /**
2262
+ * Creates a PHDocumentState with the given properties
2263
+ */
2264
+ function createDocumentState(document) {
2265
+ return {
2266
+ ...defaultDocumentState(),
2267
+ ...document
2268
+ };
2269
+ }
2270
+ /**
2271
+ * Creates a PHBaseState with the given auth and document properties
2272
+ */
2273
+ function createBaseState(auth, document) {
2274
+ return {
2275
+ auth: createAuthState(auth),
2276
+ document: createDocumentState(document)
2277
+ };
2278
+ }
2279
+ /**
2280
+ * Backfills the auth scope to the default for legacy documents serialized with
2281
+ * an empty `auth`. Replaces only `state.auth`. Idempotent.
2282
+ */
2283
+ function backfillAuthState(state) {
2284
+ return {
2285
+ ...state,
2286
+ auth: createAuthState(state.auth)
2287
+ };
2288
+ }
2289
+ function defaultGlobalState() {
2290
+ return {
2291
+ ...defaultBaseState(),
2292
+ author: {
2293
+ name: "",
2294
+ website: ""
2295
+ },
2296
+ description: "",
2297
+ extension: "",
2298
+ id: "",
2299
+ name: "",
2300
+ specifications: []
2301
+ };
2302
+ }
2303
+ function defaultLocalState() {
2304
+ return {};
2305
+ }
2306
+ function defaultPHState() {
2307
+ return {
2308
+ ...defaultBaseState(),
2309
+ global: defaultGlobalState(),
2310
+ local: defaultLocalState()
2311
+ };
2312
+ }
2313
+ function createGlobalState(state) {
2314
+ return {
2315
+ ...defaultGlobalState(),
2316
+ ...state || {}
2317
+ };
2318
+ }
2319
+ function createLocalState(state) {
2320
+ return {
2321
+ ...defaultLocalState(),
2322
+ ...state || {}
2323
+ };
2324
+ }
2325
+ function createState(baseState, globalState, localState) {
2326
+ return {
2327
+ ...createBaseState(baseState?.auth, baseState?.document),
2328
+ global: createGlobalState(globalState),
2329
+ local: createLocalState(localState)
2330
+ };
2331
+ }
2332
+ //#endregion
2333
+ //#region document-model/auth.ts
2334
+ const AUTH_ACTION_TYPES = [
2335
+ "INITIALIZE_AUTH",
2336
+ "SET_GRANT",
2337
+ "REMOVE_GRANT",
2338
+ "MOVE_GRANT"
2339
+ ];
2340
+ function isAuthAction(action) {
2341
+ return AUTH_ACTION_TYPES.includes(action.type);
2342
+ }
2343
+ /** Highest known policy version; decide() fails closed above it. */
2344
+ const MAX_SUPPORTED_AUTH_VERSION = 1;
2345
+ const InitializeAuthActionInputSchema = () => z.object({
2346
+ version: z.number().int().min(1),
2347
+ grants: z.array(GrantSchema()).max(100)
2348
+ });
2349
+ const SetGrantActionInputSchema = () => z.object({ grant: GrantSchema() });
2350
+ const RemoveGrantActionInputSchema = () => z.object({ id: z.string() });
2351
+ const MoveGrantActionInputSchema = () => z.object({
2352
+ id: z.string(),
2353
+ index: z.number()
2354
+ });
2355
+ const initializeAuth = (input) => createAction("INITIALIZE_AUTH", input, void 0, InitializeAuthActionInputSchema, "auth");
2356
+ const setGrant = (input) => createAction("SET_GRANT", input, void 0, SetGrantActionInputSchema, "auth");
2357
+ const removeGrant = (input) => createAction("REMOVE_GRANT", input, void 0, RemoveGrantActionInputSchema, "auth");
2358
+ const moveGrant = (input) => createAction("MOVE_GRANT", input, void 0, MoveGrantActionInputSchema, "auth");
2359
+ /**
2360
+ * Destructuring a null input (reachable via raw synced operations) would
2361
+ * store an engine-specific TypeError message on the error operation.
2362
+ */
2363
+ function assertActionInputShape(input) {
2364
+ if (!isPlainValue(input)) throw new InvalidActionInputError({ input: "must be an object" });
2365
+ }
2366
+ function withGrants(document, grants) {
2367
+ return {
2368
+ ...document,
2369
+ state: {
2370
+ ...document.state,
2371
+ auth: {
2372
+ ...document.state.auth,
2373
+ grants
2374
+ }
2375
+ }
2376
+ };
2377
+ }
2378
+ const P256_PUBKEY_MULTICODEC = [128, 36];
2379
+ const DID_KEY_PREFIX = "did:key:z";
2380
+ function bytesEqual(a, b) {
2381
+ if (a.length !== b.length) return false;
2382
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
2383
+ return true;
2384
+ }
2385
+ /**
2386
+ * True when `signerKey` (an ActionSigner app key, a did:key) identifies the same
2387
+ * key recorded as the document creator. Returns false
2388
+ * when there is no creator (empty JWK) or no signer key.
2389
+ */
2390
+ function isDocumentCreator(creatorKey, signerKey) {
2391
+ if (!creatorKey?.x || !creatorKey.y) return false;
2392
+ if (!signerKey || !signerKey.startsWith(DID_KEY_PREFIX)) return false;
2393
+ const decoded = base58Decode(signerKey.slice(9));
2394
+ if (!decoded || decoded.length !== 35) return false;
2395
+ if (decoded[0] !== P256_PUBKEY_MULTICODEC[0] || decoded[1] !== P256_PUBKEY_MULTICODEC[1]) return false;
2396
+ const parityPrefix = decoded[2];
2397
+ if (parityPrefix !== 2 && parityPrefix !== 3) return false;
2398
+ const didX = decoded.subarray(3, 35);
2399
+ const jwkX = base64UrlToBytes(creatorKey.x);
2400
+ const jwkY = base64UrlToBytes(creatorKey.y);
2401
+ if (jwkX.length !== 32 || jwkY.length !== 32) return false;
2402
+ if (!bytesEqual(didX, jwkX)) return false;
2403
+ return (jwkY[31] & 1) === 1 === (parityPrefix === 3);
2404
+ }
2405
+ /**
2406
+ * Sets the initial policy. Valid only while the auth scope is uninitialized
2407
+ * (version 0). The input version is the policy language version and must be an
2408
+ * integer >= 1; 0 is reserved for the uninitialized state. On a signed-header
2409
+ * document it must be signed by the document creator (`header.sig.publicKey`).
2410
+ * A creator-less policy must include a grant permitting execute on the auth
2411
+ * scope, or it would be born locked out.
2412
+ */
2413
+ function applyInitializeAuthAction(document, action) {
2414
+ assertActionInputShape(action.input);
2415
+ const { version, grants } = action.input;
2416
+ if (!Number.isInteger(version) || version < 1) throw new InvalidAuthVersionError(document.header.id, version);
2417
+ if (document.state.auth.version !== 0) throw new AuthAlreadyInitializedError(document.header.id);
2418
+ if (!Array.isArray(grants)) throw new InvalidActionInputError({ grants: "must be an array" });
2419
+ const creatorKey = document.header.sig.publicKey;
2420
+ const signerKey = action.context?.signer?.app.key;
2421
+ const hasCreator = Boolean(creatorKey.kty || creatorKey.x || creatorKey.y);
2422
+ if (hasCreator && !isDocumentCreator(creatorKey, signerKey)) throw new AuthInitializerNotCreatorError(document.header.id);
2423
+ const creator = hasCreator ? signerKey : void 0;
2424
+ assertValidInitialGrants(grants, document.header.documentType, creator);
2425
+ return {
2426
+ ...document,
2427
+ state: {
2428
+ ...document.state,
2429
+ auth: createAuthState(creator ? {
2430
+ version,
2431
+ grants,
2432
+ creator
2433
+ } : {
2434
+ version,
2435
+ grants
2436
+ })
2437
+ }
2438
+ };
2439
+ }
2440
+ /** Upserts a grant by id: replaces in place if present, otherwise appends. */
2441
+ function applySetGrantAction(document, action) {
2442
+ assertActionInputShape(action.input);
2443
+ const { grant } = action.input;
2444
+ const grants = document.state.auth.grants;
2445
+ assertValidGrantUpsert(grant, grants, document.header.documentType, document.state.auth.creator);
2446
+ return withGrants(document, grants.some((g) => g.id === grant.id) ? grants.map((g) => g.id === grant.id ? grant : g) : [...grants, grant]);
2447
+ }
2448
+ /**
2449
+ * Removes a grant by id; throws if the id is not present or if the removal
2450
+ * would leave a creator-less policy with no auth-administration grant.
2451
+ */
2452
+ function applyRemoveGrantAction(document, action) {
2453
+ assertActionInputShape(action.input);
2454
+ const { id } = action.input;
2455
+ const { grants, creator } = document.state.auth;
2456
+ if (!grants.some((g) => g.id === id)) throw new GrantNotFoundError(id);
2457
+ const next = grants.filter((g) => g.id !== id);
2458
+ assertAuthAdministrationRetained(creator, grants, next, id);
2459
+ return withGrants(document, next);
2460
+ }
2461
+ /**
2462
+ * Moves a grant by id to a new index. Order is load-bearing (the last
2463
+ * applicable grant wins), so the relative order of the other grants is kept.
2464
+ * The target index is clamped to the valid range; an unknown id throws.
2465
+ *
2466
+ * Order alone decides which grant wins, so a move can take administration away
2467
+ * without changing the list's contents. It carries the same retention rule as
2468
+ * the two mutation paths.
2469
+ */
2470
+ function applyMoveGrantAction(document, action) {
2471
+ assertActionInputShape(action.input);
2472
+ const { id, index } = action.input;
2473
+ const { grants, creator } = document.state.auth;
2474
+ const from = grants.findIndex((g) => g.id === id);
2475
+ if (from === -1) throw new GrantNotFoundError(id);
2476
+ const next = [...grants];
2477
+ const [moved] = next.splice(from, 1);
2478
+ const to = Math.max(0, Math.min(index, next.length));
2479
+ next.splice(to, 0, moved);
2480
+ assertAuthAdministrationRetained(creator, grants, next, id);
2481
+ return withGrants(document, next);
2482
+ }
2483
+ /**
2484
+ * Dispatches an auth-scope action to its handler. This is the auth scope's
2485
+ * dedicated reducer: it is applied by the base reducer instead of the model
2486
+ * reducer, mirroring the document-scope platform handlers. Unknown types are a
2487
+ * no-op, matching the model-reducer default.
2488
+ */
2489
+ function applyAuthAction(document, action) {
2490
+ switch (action.type) {
2491
+ case "INITIALIZE_AUTH": return applyInitializeAuthAction(document, action);
2492
+ case "SET_GRANT": return applySetGrantAction(document, action);
2493
+ case "REMOVE_GRANT": return applyRemoveGrantAction(document, action);
2494
+ case "MOVE_GRANT": return applyMoveGrantAction(document, action);
2495
+ default: return document;
2496
+ }
2497
+ }
2498
+ /**
2499
+ * Because only creators can initialize auth scopes, we must verify that either
2500
+ * the document has no auth or the version and creator match.
2501
+ */
2502
+ function assertAuthPreservedOnDuplicate(documentId, source, duplicated) {
2503
+ if (!source || source.version === 0) return;
2504
+ if (duplicated === void 0 || duplicated.version !== source.version || duplicated.creator !== source.creator) throw new AuthPolicyNotPreservedError(documentId);
2505
+ }
2506
+ /**
2507
+ * The auth scope a state snapshot may install, given the policy already there.
2508
+ *
2509
+ * `applyAuthAction` is the validated door onto `state.auth`, but a whole-state
2510
+ * snapshot (UPGRADE_DOCUMENT's `initialState`, LOAD_STATE's `data`) replaces the
2511
+ * scope wholesale and is authorized as a `document`-scope write. Without this,
2512
+ * a subject holding `execute` on `document` and no auth grant at all can install
2513
+ * a policy of its choosing, name itself `creator` (which exempts the policy from
2514
+ * the retention rule for good), or wipe an existing policy by carrying the
2515
+ * default uninitialized one.
2516
+ *
2517
+ * Three cases:
2518
+ *
2519
+ * - the snapshot carries no policy, or an uninitialized one: the document
2520
+ * keeps the policy it has, so a default-state upgrade cannot reset it;
2521
+ * - the document is uninitialized and the snapshot carries a policy: the
2522
+ * policy is installed after the same validation genesis applies, so it
2523
+ * cannot be born locked out;
2524
+ * - both carry a policy: they must agree. A duplicate preserves its source's
2525
+ * policy (see {@link assertAuthPreservedOnDuplicate}), and anything else is
2526
+ * an attempt to replace one policy with another.
2527
+ */
2528
+ function resolveSnapshotAuth(documentId, documentType, current, incoming) {
2529
+ const currentAuth = current ?? createAuthState({
2530
+ version: 0,
2531
+ grants: []
2532
+ });
2533
+ if (!incoming || !incoming.version) return currentAuth;
2534
+ if (currentAuth.version !== 0) {
2535
+ if (stringify(incoming) !== stringify(currentAuth)) throw new AuthPolicyNotPreservedError(documentId);
2536
+ return incoming;
2537
+ }
2538
+ if (!Array.isArray(incoming.grants)) throw new InvalidActionInputError({ grants: "must be an array" });
2539
+ assertValidInitialGrants(incoming.grants, documentType, incoming.creator);
2540
+ return incoming;
2541
+ }
2542
+ /** UNDO, REDO and PRUNE are rejected on the auth scope. */
2543
+ function assertAuthScopeActionAllowed(action) {
2544
+ if (action.scope === "auth" && [
2545
+ "UNDO",
2546
+ "REDO",
2547
+ "PRUNE"
2548
+ ].includes(action.type)) throw new AuthActionNotAllowedError(action.type);
2549
+ }
2550
+ /**
2551
+ * Evaluates the auth policy for a single request and reports why it refused.
2552
+ * Pure and deterministic.
2553
+ *
2554
+ * An uninitialized policy (version 0, absent auth state, or a legacy `{}`
2555
+ * auth scope serialized before PHAuthState had a version) leaves the document
2556
+ * open. Once a policy exists the default is deny, and grants stack in order.
2557
+ *
2558
+ * Group principals match only against a supplied groups map (the groups
2559
+ * projection, present when authGroups is on); with no map they never apply.
2560
+ * `where` clauses and { match } principals likewise evaluate only against a
2561
+ * supplied condition context (present when authConditions is on).
2562
+ */
2563
+ function evaluate(auth, subject, request, groups, conditions) {
2564
+ if (!auth || !auth.version) return { decision: "allow" };
2565
+ if (request.verb === "execute" && request.scope === "auth" && subject.key !== void 0 && subject.key === auth.creator) return { decision: "allow" };
2566
+ if (auth.version > 1) return {
2567
+ decision: "deny",
2568
+ refusal: "version-unsupported"
2569
+ };
2570
+ return evaluateGrantStack(auth.grants, subject, request, groups, conditions);
2571
+ }
2572
+ /**
2573
+ * Evaluates the auth policy for a single request. Pure and deterministic. This
2574
+ * is {@link evaluate} with the reason dropped.
2575
+ */
2576
+ function decide(auth, subject, request, groups, conditions) {
2577
+ return evaluate(auth, subject, request, groups, conditions).decision;
2578
+ }
2579
+ /**
2580
+ * The group document ids a single auth action's input names with `{ group }`
2581
+ * principals. INITIALIZE_AUTH contributes the groups named across its grants,
2582
+ * SET_GRANT the groups named by its one grant; REMOVE_GRANT and MOVE_GRANT
2583
+ * contribute nothing. Total over any input shape, because references are read
2584
+ * from the input as it arrived, including inputs later stored as errors.
2585
+ */
2586
+ function mentionedGroupIds(action) {
2587
+ const input = action.input;
2588
+ const candidates = [];
2589
+ if (action.type === "INITIALIZE_AUTH" && Array.isArray(input?.grants)) candidates.push(...input.grants);
2590
+ if (action.type === "SET_GRANT" && input?.grant !== void 0) candidates.push(input.grant);
2591
+ const ids = [];
2592
+ for (const candidate of candidates) {
2593
+ if (typeof candidate !== "object" || candidate === null) continue;
2594
+ const principal = candidate.principal;
2595
+ if (typeof principal !== "object" || principal === null) continue;
2596
+ const group = principal.group;
2597
+ if (typeof group === "string" && group !== "" && !ids.includes(group)) ids.push(group);
2598
+ }
2599
+ return ids;
2600
+ }
2601
+ //#endregion
2602
+ //#region document-model/denied.ts
2603
+ /**
2604
+ * True iff authorization rejected the action.
2605
+ */
2606
+ function isDenied(operation) {
2607
+ return operation.deniedReason !== void 0;
2608
+ }
2609
+ /**
2610
+ * The closed set of strings persisted as `deniedReason`. Re-evaluation compares
2611
+ * them, so they are consensus data: exact strings that embed no grant id,
2612
+ * subject or timestamp. Changing one is history-visible.
2613
+ */
2614
+ const DOCUMENT_DELETED_REASON = "document deleted";
2615
+ const AUTH_VERSION_UNSUPPORTED_REASON = "auth policy version unsupported";
2616
+ const AUTH_NO_GRANT_REASON = "no grant permits this operation";
2617
+ const AUTH_DENIED_BY_GRANT_REASON = "denied by grant";
1441
2618
  //#endregion
1442
2619
  //#region document-model/document-schema.ts
1443
2620
  const BaseDocumentHeaderSchema = z.object({
@@ -1710,6 +2887,7 @@ function createDocumentScopeOperations(header, state) {
1710
2887
  function baseCreateDocument(createState, initialState, documentType = "") {
1711
2888
  const state = createState(initialState);
1712
2889
  const header = createPresignedHeader(generateId(), documentType);
2890
+ header.protocolVersions = { "base-reducer": 2 };
1713
2891
  return {
1714
2892
  header,
1715
2893
  state,
@@ -1805,6 +2983,18 @@ function mapSkippedOperationsV2(operations) {
1805
2983
  * Uses the V2 model where consecutive NOOPs form chains.
1806
2984
  * Unlike V1 garbageCollect, this preserves ALL operations but marks which to apply.
1807
2985
  */
2986
+ /**
2987
+ * The base-reducer protocol version a document is written against. Every
2988
+ * document carries one, set from the CREATE_DOCUMENT input. A header without
2989
+ * one was built outside that path, and choosing a version on its behalf would
2990
+ * replay the document through a reducer it was not written for, so it is an
2991
+ * error rather than a default.
2992
+ */
2993
+ function baseReducerVersion(header) {
2994
+ const version = header.protocolVersions?.["base-reducer"];
2995
+ if (typeof version !== "number") throw new Error(`Document ${header.id} carries no base-reducer protocol version`);
2996
+ return version;
2997
+ }
1808
2998
  function garbageCollectV2(sortedOperations) {
1809
2999
  const result = [];
1810
3000
  let noopChainLength = 0;
@@ -1824,9 +3014,26 @@ function sortMappedOperations(operations) {
1824
3014
  const defaultCreateState = (state) => {
1825
3015
  return state;
1826
3016
  };
3017
+ /**
3018
+ * Records an operation in the history without applying it, which is what a
3019
+ * denied operation needs: it occupies its index and contributes no state.
3020
+ *
3021
+ * The scope defaults to the action's own, and is passed explicitly by a rebuild
3022
+ * that is walking one stream and does not want to trust the action's copy.
3023
+ */
3024
+ function appendWithoutApplying(document, operation, scope = operation.action.scope) {
3025
+ return {
3026
+ ...document,
3027
+ operations: {
3028
+ ...document.operations,
3029
+ [scope]: [...document.operations[scope] ?? [], operation]
3030
+ }
3031
+ };
3032
+ }
1827
3033
  function replayDocument(initialState, operations, reducer, header, dispatch, skipHeaderOperations = {}, options) {
1828
3034
  const { checkHashes = true, reuseOperationResultingState, operationResultingStateParser = parseResultingState, skipIndexValidation } = options || {};
1829
- let documentState = initialState;
3035
+ const backfilledInitialState = backfillAuthState(initialState);
3036
+ let documentState = backfilledInitialState;
1830
3037
  const operationsToReplay = [];
1831
3038
  const allScopes = new Set([
1832
3039
  ...Object.keys(operations),
@@ -1861,12 +3068,13 @@ function replayDocument(initialState, operations, reducer, header, dispatch, ski
1861
3068
  const document = {
1862
3069
  header,
1863
3070
  state: defaultCreateState(documentState),
1864
- initialState,
3071
+ initialState: backfilledInitialState,
1865
3072
  operations: initialOperations,
1866
3073
  clipboard: []
1867
3074
  };
1868
3075
  let result = document;
1869
3076
  if (operationsToReplay.length) result = operationsToReplay.reduce((document, operation) => {
3077
+ if (isDenied(operation)) return updateHeaderRevision(appendWithoutApplying(document, operation), operation.action.scope, operation.timestampUtcMs);
1870
3078
  return reducer(document, operation.action, dispatch, {
1871
3079
  ignoreSkipOperations: true,
1872
3080
  checkHashes,
@@ -2390,15 +3598,32 @@ function redoOperation(document, action, skip) {
2390
3598
  });
2391
3599
  }
2392
3600
  function loadStateOperation(document, action) {
3601
+ const loaded = backfillAuthState(action.state.data);
3602
+ loaded.auth = resolveSnapshotAuth(document.header.id, document.header.documentType, backfillAuthState({ ...document.state }).auth, loaded.auth);
2393
3603
  return {
2394
3604
  ...document,
2395
3605
  header: {
2396
3606
  ...document.header,
2397
3607
  name: action.state.name
2398
3608
  },
2399
- state: action.state.data
3609
+ state: loaded
2400
3610
  };
2401
3611
  }
3612
+ /**
3613
+ * Reads an operation's outcome. A denial takes precedence over a reducer
3614
+ * error, since a denied operation never reaches its reducer.
3615
+ */
3616
+ function operationOutcome(operation) {
3617
+ if (operation.deniedReason !== void 0) return {
3618
+ kind: "denied",
3619
+ reason: operation.deniedReason
3620
+ };
3621
+ if (operation.error !== void 0) return {
3622
+ kind: "reducer-error",
3623
+ message: operation.error
3624
+ };
3625
+ return { kind: "applied" };
3626
+ }
2402
3627
  //#endregion
2403
3628
  //#region document-model/reducer.ts
2404
3629
  function replayOperations(initialState, clearedOperations, stateReducer, header, dispatch, documentReducer = baseReducer, skipHeaderOperations = {}, options) {
@@ -2572,12 +3797,13 @@ function processUndoOperation(document, scope, customReducer, reuseOperationResu
2572
3797
  function baseReducer(document, action, customReducer, dispatch, options = {}) {
2573
3798
  const { skip, ignoreSkipOperations = false, reuseOperationResultingState = false, operationResultingStateParser, pruneOnSkip = true, branch = "main" } = options;
2574
3799
  let _action = actionFromAction(action);
3800
+ assertAuthScopeActionAllowed(_action);
2575
3801
  let skipValue = skip ?? options.replayOptions?.operation.skip ?? 0;
2576
3802
  let newDocument = { ...document };
2577
3803
  let reuseLastOperationIndex = false;
2578
3804
  const shouldProcessSkipOperation = !ignoreSkipOperations && skipValue > 0;
2579
3805
  if (isUndoRedo(_action)) {
2580
- const { skip: calculatedSkip, action: transformedAction, document: processedDocument, reuseLastOperationIndex: reuseIndex } = processUndoRedo(document, _action, skipValue, options.protocolVersion ?? 1);
3806
+ const { skip: calculatedSkip, action: transformedAction, document: processedDocument, reuseLastOperationIndex: reuseIndex } = processUndoRedo(document, _action, skipValue, options.protocolVersion ?? baseReducerVersion(document.header));
2581
3807
  _action = transformedAction;
2582
3808
  skipValue = calculatedSkip;
2583
3809
  newDocument = processedDocument;
@@ -2593,7 +3819,7 @@ function baseReducer(document, action, customReducer, dispatch, options = {}) {
2593
3819
  branch
2594
3820
  };
2595
3821
  newDocument = updateDocument(newDocument, _action, reuseLastOperationIndex, skipValue, operationContext, options.replayOptions?.operation, options.skipIndexValidation);
2596
- const protocolVersion = options.protocolVersion ?? 1;
3822
+ const protocolVersion = options.protocolVersion ?? baseReducerVersion(document.header);
2597
3823
  if (isUndo(action) && protocolVersion < 2) return processUndoOperation(newDocument, action.scope, customReducer);
2598
3824
  const isNoopWithSkip = _action.type === "NOOP" && skipValue > 0;
2599
3825
  if ((isUndo(action) || isNoopWithSkip) && protocolVersion >= 2) {
@@ -2619,6 +3845,13 @@ function baseReducer(document, action, customReducer, dispatch, options = {}) {
2619
3845
  }
2620
3846
  newDocument = create(newDocument, (draft) => {
2621
3847
  try {
3848
+ if (_action.scope === "auth") {
3849
+ const authState = applyAuthAction(newDocument, _action).state;
3850
+ unsafe(() => {
3851
+ draft.state = castDraft(authState);
3852
+ });
3853
+ return;
3854
+ }
2622
3855
  const newState = customReducer(draft.state, _action, dispatch);
2623
3856
  if (newState) unsafe(() => {
2624
3857
  draft.state = castDraft(newState);
@@ -3414,14 +4647,27 @@ const documentModelStateReducer = (state, action) => {
3414
4647
  const documentModelReducer = createReducer(documentModelStateReducer);
3415
4648
  //#endregion
3416
4649
  //#region document-model/upgrades.ts
4650
+ /**
4651
+ * Canonical document-model version normalization: documents stamped with 0
4652
+ * or nothing at all predate versioning and are treated as version 1, the
4653
+ * same version the registry assigns unversioned modules. Every consumer
4654
+ * that resolves a module or compares versions must use this rule; resolving
4655
+ * 0 to "latest" instead re-pins a legacy document's history to whichever
4656
+ * module happens to be newest.
4657
+ */
4658
+ function normalizeDocumentModelVersion(version) {
4659
+ return version && version > 0 ? version : 1;
4660
+ }
3417
4661
  function applyInitialState(document, action) {
3418
4662
  const input = action.input;
3419
4663
  const newState = input.initialState || input.state;
3420
4664
  if (newState) {
3421
- document.state = {
4665
+ const merged = backfillAuthState({
3422
4666
  ...document.state,
3423
4667
  ...newState
3424
- };
4668
+ });
4669
+ merged.auth = resolveSnapshotAuth(document.header.id, document.header.documentType, backfillAuthState({ ...document.state }).auth, merged.auth);
4670
+ document.state = merged;
3425
4671
  document.initialState = document.state;
3426
4672
  }
3427
4673
  }
@@ -3483,7 +4729,6 @@ function computeUpgradeTransitions(manifest, fromVersion, toVersion) {
3483
4729
  }
3484
4730
  //#endregion
3485
4731
  //#region document-model/versioned-replay.ts
3486
- const NON_DOMAIN_SCOPES$1 = new Set(["auth", "document"]);
3487
4732
  function highestReducerVersion(reducers) {
3488
4733
  const keys = Object.keys(reducers).map(Number);
3489
4734
  if (keys.length === 0) throw new Error("VersionedReplayConfig.reducers must not be empty");
@@ -3511,15 +4756,15 @@ function highestReducerVersion(reducers) {
3511
4756
  */
3512
4757
  function replayDocumentVersioned(initialState, operations, config, header, dispatch, options) {
3513
4758
  const { checkHashes = true, skipIndexValidation } = options || {};
3514
- const protocolVersion = header.protocolVersions?.["base-reducer"] ?? 1;
4759
+ const protocolVersion = baseReducerVersion(header);
3515
4760
  const spine = (operations["document"] ?? []).slice().sort((a, b) => a.index - b.index);
3516
4761
  const upgrades = spine.filter((op) => op.action.type === "UPGRADE_DOCUMENT");
3517
4762
  const legacyFallback = () => {
3518
- const domainOps = Object.fromEntries(Object.entries(operations).filter(([s]) => !NON_DOMAIN_SCOPES$1.has(s)));
4763
+ const replayOps = Object.fromEntries(Object.entries(operations).filter(([s]) => s !== "document"));
3519
4764
  const latestVersion = highestReducerVersion(config.reducers);
3520
4765
  const reducer = config.reducers[latestVersion];
3521
4766
  return {
3522
- ...replayDocument(initialState, domainOps, reducer, header, dispatch, {}, options),
4767
+ ...replayDocument(initialState, replayOps, reducer, header, dispatch, {}, options),
3523
4768
  operations
3524
4769
  };
3525
4770
  };
@@ -3543,14 +4788,14 @@ function replayDocumentVersioned(initialState, operations, config, header, dispa
3543
4788
  const a = op.action;
3544
4789
  return a.input.fromVersion > 0 && a.input.fromVersion < a.input.toVersion;
3545
4790
  });
3546
- const domainScopes = Object.keys(operations).filter((s) => !NON_DOMAIN_SCOPES$1.has(s));
4791
+ const replayScopes = Object.keys(operations).filter((s) => s !== "document");
3547
4792
  const scopeOps = {};
3548
- for (const s of domainScopes) scopeOps[s] = (operations[s] ?? []).slice().sort((a, b) => a.index - b.index);
4793
+ for (const s of replayScopes) scopeOps[s] = (operations[s] ?? []).slice().sort((a, b) => a.index - b.index);
3549
4794
  const boundaries = validatedUpgrades.map((upgradeOp) => {
3550
4795
  const revisionSnapshot = upgradeOp.action.input.revision;
3551
4796
  const upgradeTimestamp = upgradeOp.timestampUtcMs;
3552
4797
  const boundary = {};
3553
- for (const s of domainScopes) {
4798
+ for (const s of replayScopes) {
3554
4799
  const ops = scopeOps[s] ?? [];
3555
4800
  if (revisionSnapshot !== void 0) {
3556
4801
  const rev = revisionSnapshot[s] ?? 0;
@@ -3568,7 +4813,7 @@ function replayDocumentVersioned(initialState, operations, config, header, dispa
3568
4813
  }
3569
4814
  return boundary;
3570
4815
  });
3571
- for (let i = 1; i < boundaries.length; i++) for (const s of domainScopes) {
4816
+ for (let i = 1; i < boundaries.length; i++) for (const s of replayScopes) {
3572
4817
  const prev = boundaries[i - 1]?.[s] ?? 0;
3573
4818
  const curr = boundaries[i]?.[s] ?? 0;
3574
4819
  if (boundaries[i]) boundaries[i][s] = Math.max(prev, curr);
@@ -3580,10 +4825,11 @@ function replayDocumentVersioned(initialState, operations, config, header, dispa
3580
4825
  ]);
3581
4826
  const initialOperations = {};
3582
4827
  for (const s of allScopes) initialOperations[s] = [];
4828
+ const backfilledSeed = backfillAuthState(seedState);
3583
4829
  let document = {
3584
4830
  header,
3585
- state: seedState,
3586
- initialState: seedState,
4831
+ state: backfilledSeed,
4832
+ initialState: backfilledSeed,
3587
4833
  operations: initialOperations,
3588
4834
  clipboard: []
3589
4835
  };
@@ -3591,17 +4837,15 @@ function replayDocumentVersioned(initialState, operations, config, header, dispa
3591
4837
  const segmentEndHashPerScope = /* @__PURE__ */ new Map();
3592
4838
  for (let k = 0; k <= validatedUpgrades.length; k++) {
3593
4839
  const reducer = config.reducers[currentVersion];
3594
- if (!reducer) {
3595
- const available = Object.keys(config.reducers).join(", ");
3596
- throw new Error(`No reducer registered for document version ${currentVersion}. Available versions: ${available}`);
3597
- }
3598
- for (const s of domainScopes) {
4840
+ if (!reducer) throw new UnsupportedDocumentModelVersionError(header.documentType, currentVersion, Object.keys(config.reducers).map(Number).sort((a, b) => a - b));
4841
+ for (const s of replayScopes) {
3599
4842
  const ops = scopeOps[s] ?? [];
3600
4843
  const segStart = k === 0 ? 0 : boundaries[k - 1]?.[s] ?? 0;
3601
4844
  const segEnd = k < validatedUpgrades.length ? boundaries[k]?.[s] ?? ops.length : ops.length;
3602
4845
  const segOps = ops.slice(segStart, segEnd);
3603
4846
  for (const op of segOps) {
3604
- document = reducer(document, op.action, dispatch, {
4847
+ if (isDenied(op)) document = updateHeaderRevision(appendWithoutApplying(document, op, s), s, op.timestampUtcMs);
4848
+ else document = reducer(document, op.action, dispatch, {
3605
4849
  ignoreSkipOperations: true,
3606
4850
  checkHashes,
3607
4851
  skipIndexValidation,
@@ -3618,6 +4862,7 @@ function replayDocumentVersioned(initialState, operations, config, header, dispa
3618
4862
  if (!spineOp) continue;
3619
4863
  const spineActionType = spineOp.action.type;
3620
4864
  if (spineActionType === "CREATE_DOCUMENT" || spineActionType === "UPGRADE_DOCUMENT") continue;
4865
+ if (isDenied(spineOp)) continue;
3621
4866
  if (spineActionType === "DELETE_DOCUMENT") document = applyDeleteDocumentAction(document, spineOp.action);
3622
4867
  else document = reducer(document, spineOp.action, dispatch, {
3623
4868
  ignoreSkipOperations: true,
@@ -3648,7 +4893,7 @@ function replayDocumentVersioned(initialState, operations, config, header, dispa
3648
4893
  }
3649
4894
  };
3650
4895
  if (!checkHashes) {
3651
- const allReplayedOps = domainScopes.flatMap((s) => scopeOps[s] ?? []);
4896
+ const allReplayedOps = replayScopes.flatMap((s) => scopeOps[s] ?? []);
3652
4897
  for (const scope of Object.keys(document.state)) {
3653
4898
  const capturedHash = segmentEndHashPerScope.get(scope);
3654
4899
  const scopeHash = capturedHash !== void 0 ? capturedHash : hashDocumentStateForScope(document, scope);
@@ -3692,7 +4937,6 @@ function replayDocumentVersioned(initialState, operations, config, header, dispa
3692
4937
  }
3693
4938
  //#endregion
3694
4939
  //#region document-model/files.ts
3695
- const NON_DOMAIN_SCOPES = new Set(["auth", "document"]);
3696
4940
  function zipAsync(data) {
3697
4941
  return new Promise((resolve, reject) => {
3698
4942
  zip(data, (err, out) => err ? reject(err) : resolve(out));
@@ -3799,7 +5043,7 @@ async function parseZipData(data) {
3799
5043
  async function loadFromZipData(data, reducer, options) {
3800
5044
  const { initialState, header, clearedOperations } = await parseZipData(data);
3801
5045
  return {
3802
- ...replayDocument(initialState, Object.fromEntries(Object.entries(clearedOperations).filter(([scope]) => !NON_DOMAIN_SCOPES.has(scope))), reducer, header, void 0, {}, options),
5046
+ ...replayDocument(initialState, Object.fromEntries(Object.entries(clearedOperations).filter(([scope]) => scope !== "document")), reducer, header, void 0, {}, options),
3803
5047
  operations: clearedOperations
3804
5048
  };
3805
5049
  }
@@ -3835,105 +5079,6 @@ const getFileBrowser = (file) => {
3835
5079
  return Promise.resolve().then(() => readFileBrowser(file));
3836
5080
  };
3837
5081
  //#endregion
3838
- //#region document-model/state.ts
3839
- /**
3840
- * Creates a default PHAuthState
3841
- */
3842
- function defaultAuthState() {
3843
- return {};
3844
- }
3845
- /**
3846
- * Creates a default PHDocumentState
3847
- */
3848
- function defaultDocumentState() {
3849
- return {
3850
- version: 0,
3851
- hash: {
3852
- algorithm: HASH_ALGORITHM_SHA1,
3853
- encoding: HASH_ENCODING_BASE64
3854
- }
3855
- };
3856
- }
3857
- /**
3858
- * Creates a default PHBaseState with auth and document properties
3859
- */
3860
- function defaultBaseState() {
3861
- return {
3862
- auth: defaultAuthState(),
3863
- document: defaultDocumentState()
3864
- };
3865
- }
3866
- /**
3867
- * Creates a PHAuthState with the given properties
3868
- */
3869
- function createAuthState(auth) {
3870
- return {
3871
- ...defaultAuthState(),
3872
- ...auth
3873
- };
3874
- }
3875
- /**
3876
- * Creates a PHDocumentState with the given properties
3877
- */
3878
- function createDocumentState(document) {
3879
- return {
3880
- ...defaultDocumentState(),
3881
- ...document
3882
- };
3883
- }
3884
- /**
3885
- * Creates a PHBaseState with the given auth and document properties
3886
- */
3887
- function createBaseState(auth, document) {
3888
- return {
3889
- auth: createAuthState(auth),
3890
- document: createDocumentState(document)
3891
- };
3892
- }
3893
- function defaultGlobalState() {
3894
- return {
3895
- ...defaultBaseState(),
3896
- author: {
3897
- name: "",
3898
- website: ""
3899
- },
3900
- description: "",
3901
- extension: "",
3902
- id: "",
3903
- name: "",
3904
- specifications: []
3905
- };
3906
- }
3907
- function defaultLocalState() {
3908
- return {};
3909
- }
3910
- function defaultPHState() {
3911
- return {
3912
- ...defaultBaseState(),
3913
- global: defaultGlobalState(),
3914
- local: defaultLocalState()
3915
- };
3916
- }
3917
- function createGlobalState(state) {
3918
- return {
3919
- ...defaultGlobalState(),
3920
- ...state || {}
3921
- };
3922
- }
3923
- function createLocalState(state) {
3924
- return {
3925
- ...defaultLocalState(),
3926
- ...state || {}
3927
- };
3928
- }
3929
- function createState(baseState, globalState, localState) {
3930
- return {
3931
- ...createBaseState(baseState?.auth, baseState?.document),
3932
- global: createGlobalState(globalState),
3933
- local: createLocalState(localState)
3934
- };
3935
- }
3936
- //#endregion
3937
- export { AddChangeLogItemInputSchema, AddModuleInputSchema, AddOperationErrorInputSchema, AddOperationExampleInputSchema, AddOperationInputSchema, AddStateExampleInputSchema, AuthorSchema, BaseDocumentHeaderSchema, BaseDocumentStateSchema, CodeExampleSchema, ConfigEntrySchema, ConfigEntryTypeSchema, DeleteChangeLogItemInputSchema, DeleteModuleInputSchema, DeleteOperationErrorInputSchema, DeleteOperationExampleInputSchema, DeleteOperationInputSchema, DeleteStateExampleInputSchema, DocumentActionSchema, DocumentModelGlobalStateSchema, DocumentModelHeaderSchema, DocumentModelInputSchema, DocumentModelPHStateSchema, DocumentModelSchema, DocumentSpecificationSchema, DowngradeNotSupportedError, FileSystemError, HASH_ALGORITHM_SHA1, HASH_ALGORITHM_SHA256, HASH_ALGORITHM_SHA512, HASH_ENCODING_BASE64, HASH_ENCODING_HEX, HashMismatchError, IntegrityIssueSubType, IntegrityIssueType, InvalidActionInputError, InvalidActionInputZodError, LoadStateActionInputSchema, LoadStateActionSchema, LoadStateActionStateInputSchema, Load_StateSchema, ManifestSchema, ModuleSchema, MoveOperationInputSchema, OPERATION_NAME_PATTERN, OperationErrorSchema, OperationScopeSchema, OperationSpecificationSchema, PowerhouseModuleSchema, PowerhouseModulesSchema, PruneActionInputSchema, PruneActionSchema, PruneSchema, PublisherSchema, RESERVED_OPERATION_NAMES, RedoActionInputSchema, RedoActionSchema, RedoSchema, ReorderChangeLogItemsInputSchema, ReorderModuleOperationsInputSchema, ReorderModulesInputSchema, ReorderOperationErrorsInputSchema, ReorderOperationExamplesInputSchema, ReorderStateExamplesInputSchema, ScopeStateSchema, SetAuthorNameInputSchema, SetAuthorWebsiteInputSchema, SetInitialStateInputSchema, SetModelDescriptionInputSchema, SetModelExtensionInputSchema, SetModelIdInputSchema, SetModelNameInputSchema, SetModuleDescriptionInputSchema, SetModuleNameInputSchema, SetNameActionInputSchema, SetNameActionSchema, SetOperationDescriptionInputSchema, SetOperationErrorCodeInputSchema, SetOperationErrorDescriptionInputSchema, SetOperationErrorNameInputSchema, SetOperationErrorTemplateInputSchema, SetOperationNameInputSchema, SetOperationReducerInputSchema, SetOperationSchemaInputSchema, SetOperationScopeInputSchema, SetOperationTemplateInputSchema, SetPreferredEditorActionInputSchema, SetPreferredEditorActionSchema, SetStateSchemaInputSchema, Set_NameSchema, Set_PreferredEditorSchema, StateSchema, UndoActionInputSchema, UndoActionSchema, UndoSchema, UpdateChangeLogItemInputSchema, UpdateOperationExampleInputSchema, UpdateStateExampleInputSchema, ab2hex, actionContext, actionFromAction, actionSigner, actions, addChangeLogItem, addModule, addOperation, addOperationError, addOperationExample, addStateExample, addUndo, applyDeleteDocumentAction, applyUpgradeDocumentAction, assertIsDocumentModelDocument, assertIsDocumentModelState, assertModuleIdUnique, assertOperationErrorIdUnique, assertOperationExampleIdUnique, assertOperationIdUnique, attachBranch, baseActions, baseCreateDocument, baseLoadFromInput, baseLoadFromInputVersioned, baseReducer, baseSaveToFileHandle, buildOperationSignature, buildOperationSignatureMessage, buildOperationSignatureParams, buildSignedAction, checkCleanedOperationsIntegrity, checkOperationsIntegrity, computeUpgradeTransitions, createAction, createAuthState, createBaseState, createDocumentState, createGlobalState, createLocalState, createMinimalZip, createPresignedHeader, createReducer, createSignedHeader, createSignedHeaderForSigner, createState, createVerificationSigner, createZip, defaultAuthState, defaultBaseState, defaultDocumentState, defaultGlobalState, defaultLocalState, defaultPHState, definedNonNullAnySchema, deleteChangeLogItem, deleteModule, deleteOperation, deleteOperationError, deleteOperationExample, deleteStateExample, deriveOperationId, diffOperations, documentModelActions, documentModelDocumentType, documentModelFileExtension, documentModelGlobalState, documentModelHeaderReducer, documentModelInitialGlobalState, documentModelInitialLocalState, documentModelLoadFromInput, documentModelModuleReducer, documentModelOperationErrorReducer, documentModelOperationExampleReducer, documentModelOperationReducer, documentModelReducer, documentModelSaveToFileHandle, documentModelStateReducer, documentModelStateSchemaReducer, documentModelVersioningReducer, fetchFileBrowser, filterDocumentOperationsResultingState, filterDuplicatedOperations, findModuleOrThrow, findOperationErrorOrThrow, findOperationExampleOrThrow, findOperationOrThrow, garbageCollect, garbageCollectDocumentOperations, garbageCollectV2, generateId, generateMock, getAllOperationNames, getDocumentLastModified, getFileBrowser, getUnixTimestamp, groupOperationsByScope, hashBrowser, hashDocumentStateForScope, hex2ab, isDefinedNonNullAny, isDocumentAction, isDocumentModelDocument, isDocumentModelState, isNoopOperation, isReservedOperationName, isUndo, isUndoRedo, isValidOperationNameFormat, loadState, loadStateOperation, mapSkippedOperations, mapSkippedOperationsV2, merge, moveOperation, nextSkipNumber, noop, operationExampleCreators, operationFromAction, operationFromOperation, operationWithContext, operationsAreEqual, parseResultingState, precedes, prepareOperations, processUndoRedo, prune, pruneOperation, readFileBrowser, readOnly, redo, redoOperation, releaseNewVersion, removeExistingOperations, reorderChangeLogItems, reorderModuleOperations, reorderModules, reorderOperationErrors, reorderOperationExamples, reorderStateExamples, replayDocument, replayDocumentVersioned, replayOperations, reshuffleByTimestamp, reshuffleByTimestampAndIndex, setAuthorName, setAuthorWebsite, setInitialState, setModelDescription, setModelExtension, setModelId, setModelName, setModuleDescription, setModuleName, setName, setNameOperation, setOperationDescription, setOperationErrorCode, setOperationErrorDescription, setOperationErrorName, setOperationErrorTemplate, setOperationName, setOperationReducer, setOperationSchema, setOperationScope, setOperationTemplate, setPreferredEditor, setPreferredEditorOperation, setStateSchema, sign, skipHeaderOperations, sortMappedOperations, sortOperations, split, undo, undoOperation, undoOperationV2, updateChangeLogItem, updateDocument, updateHeaderRevision, updateOperationExample, updateStateExample, validateHeader, validateInitialState, validateModule, validateModuleOperation, validateModules, validateOperationName, validateOperations, validateStateSchemaName, verify, verifyOperationSignature, writeFileBrowser };
5082
+ export { AUTH_ACTION_TYPES, AUTH_DENIED_BY_GRANT_REASON, AUTH_NO_GRANT_REASON, AUTH_VERSION_UNSUPPORTED_REASON, AddChangeLogItemInputSchema, AddModuleInputSchema, AddOperationErrorInputSchema, AddOperationExampleInputSchema, AddOperationInputSchema, AddStateExampleInputSchema, AuthActionNotAllowedError, AuthAdministrationLockoutError, AuthAdministrationMissingError, AuthAlreadyInitializedError, AuthInitializerNotCreatorError, AuthPolicyNotPreservedError, AuthorSchema, BaseDocumentHeaderSchema, BaseDocumentStateSchema, CodeExampleSchema, ConfigEntrySchema, ConfigEntryTypeSchema, DOCUMENT_DELETED_REASON, DeleteChangeLogItemInputSchema, DeleteModuleInputSchema, DeleteOperationErrorInputSchema, DeleteOperationExampleInputSchema, DeleteOperationInputSchema, DeleteStateExampleInputSchema, DocumentActionSchema, DocumentModelGlobalStateSchema, DocumentModelHeaderSchema, DocumentModelInputSchema, DocumentModelPHStateSchema, DocumentModelSchema, DocumentSpecificationSchema, DowngradeNotSupportedError, FileSystemError, GrantNotFoundError, GrantSchema, GroupPrincipalNotAllowedError, HASH_ALGORITHM_SHA1, HASH_ALGORITHM_SHA256, HASH_ALGORITHM_SHA512, HASH_ENCODING_BASE64, HASH_ENCODING_HEX, HashMismatchError, InitializeAuthActionInputSchema, IntegrityIssueSubType, IntegrityIssueType, InvalidActionInputError, InvalidActionInputZodError, InvalidAuthVersionError, InvalidGrantError, LoadStateActionInputSchema, LoadStateActionSchema, LoadStateActionStateInputSchema, Load_StateSchema, MAX_AUTH_GRANTS, MAX_CAPABILITY_OPERATIONS, MAX_CONDITION_DEPTH, MAX_CONDITION_NODES, MAX_SUPPORTED_AUTH_VERSION, ManifestSchema, ModuleSchema, MoveGrantActionInputSchema, MoveOperationInputSchema, OPERATION_NAME_PATTERN, OperationErrorSchema, OperationScopeSchema, OperationSpecificationSchema, PowerhouseModuleSchema, PowerhouseModulesSchema, PruneActionInputSchema, PruneActionSchema, PruneSchema, PublisherSchema, PwaConfigSchema, RESERVED_OPERATION_NAMES, RedoActionInputSchema, RedoActionSchema, RedoSchema, RemoveGrantActionInputSchema, ReorderChangeLogItemsInputSchema, ReorderModuleOperationsInputSchema, ReorderModulesInputSchema, ReorderOperationErrorsInputSchema, ReorderOperationExamplesInputSchema, ReorderStateExamplesInputSchema, ScopeStateSchema, SetAuthorNameInputSchema, SetAuthorWebsiteInputSchema, SetGrantActionInputSchema, SetInitialStateInputSchema, SetModelDescriptionInputSchema, SetModelExtensionInputSchema, SetModelIdInputSchema, SetModelNameInputSchema, SetModuleDescriptionInputSchema, SetModuleNameInputSchema, SetNameActionInputSchema, SetNameActionSchema, SetOperationDescriptionInputSchema, SetOperationErrorCodeInputSchema, SetOperationErrorDescriptionInputSchema, SetOperationErrorNameInputSchema, SetOperationErrorTemplateInputSchema, SetOperationNameInputSchema, SetOperationReducerInputSchema, SetOperationSchemaInputSchema, SetOperationScopeInputSchema, SetOperationTemplateInputSchema, SetPreferredEditorActionInputSchema, SetPreferredEditorActionSchema, SetStateSchemaInputSchema, Set_NameSchema, Set_PreferredEditorSchema, StateSchema, UndoActionInputSchema, UndoActionSchema, UndoSchema, UnsupportedDocumentModelVersionError, UpdateChangeLogItemInputSchema, UpdateOperationExampleInputSchema, UpdateStateExampleInputSchema, ab2hex, actionContext, actionFromAction, actionSigner, actions, addChangeLogItem, addModule, addOperation, addOperationError, addOperationExample, addStateExample, addUndo, appendWithoutApplying, applyAuthAction, applyDeleteDocumentAction, applyInitializeAuthAction, applyMoveGrantAction, applyRemoveGrantAction, applySetGrantAction, applyUpgradeDocumentAction, assertAuthAdministrationRetained, assertAuthPreservedOnDuplicate, assertAuthScopeActionAllowed, assertIsDocumentModelDocument, assertIsDocumentModelState, assertModuleIdUnique, assertOperationErrorIdUnique, assertOperationExampleIdUnique, assertOperationIdUnique, assertValidGrant, assertValidGrantUpsert, assertValidInitialGrants, attachBranch, backfillAuthState, base58Decode, base64UrlToBytes, baseActions, baseCreateDocument, baseLoadFromInput, baseLoadFromInputVersioned, baseReducer, baseReducerVersion, baseSaveToFileHandle, buildOperationSignature, buildOperationSignatureMessage, buildOperationSignatureParams, buildSignedAction, checkCleanedOperationsIntegrity, checkOperationsIntegrity, computeUpgradeTransitions, createAction, createAuthState, createBaseState, createDocumentState, createGlobalState, createLocalState, createMinimalZip, createPresignedHeader, createReducer, createSignedHeader, createSignedHeaderForSigner, createState, createVerificationSigner, createZip, decide, defaultAuthState, defaultBaseState, defaultDocumentState, defaultGlobalState, defaultLocalState, defaultPHState, definedNonNullAnySchema, deleteChangeLogItem, deleteModule, deleteOperation, deleteOperationError, deleteOperationExample, deleteStateExample, deriveOperationId, deserializeSignature, diffOperations, documentModelActions, documentModelDocumentType, documentModelFileExtension, documentModelGlobalState, documentModelHeaderReducer, documentModelInitialGlobalState, documentModelInitialLocalState, documentModelLoadFromInput, documentModelModuleReducer, documentModelOperationErrorReducer, documentModelOperationExampleReducer, documentModelOperationReducer, documentModelReducer, documentModelSaveToFileHandle, documentModelStateReducer, documentModelStateSchemaReducer, documentModelVersioningReducer, evaluate, evaluateCondition, evaluateGrantStack, evaluateGrants, fetchFileBrowser, filterDocumentOperationsResultingState, filterDuplicatedOperations, findModuleOrThrow, findOperationErrorOrThrow, findOperationExampleOrThrow, findOperationOrThrow, garbageCollect, garbageCollectDocumentOperations, garbageCollectV2, generateId, generateMock, getAllOperationNames, getDocumentLastModified, getFileBrowser, getUnixTimestamp, grantProblem, groupDocumentType, groupMembershipActionTypes, groupOperationsByScope, hashBrowser, hashDocumentStateForScope, hex2ab, initializeAuth, isAuthAction, isDefinedNonNullAny, isDenied, isDocumentAction, isDocumentCreator, isDocumentModelDocument, isDocumentModelState, isNoopOperation, isPlainValue, isReservedOperationName, isUndo, isUndoRedo, isValidOperationNameFormat, loadState, loadStateOperation, mapSkippedOperations, mapSkippedOperationsV2, mentionedGroupIds, merge, moveGrant, moveOperation, nextSkipNumber, noop, normalizeDocumentModelVersion, operationExampleCreators, operationFromAction, operationFromOperation, operationOutcome, operationWithContext, operationsAreEqual, parseResultingState, precedes, prepareOperations, processUndoRedo, prune, pruneOperation, readFileBrowser, readOnly, redo, redoOperation, referencedGroupIds, releaseNewVersion, removeExistingOperations, removeGrant, reorderChangeLogItems, reorderModuleOperations, reorderModules, reorderOperationErrors, reorderOperationExamples, reorderStateExamples, replayDocument, replayDocumentVersioned, replayOperations, reshuffleByTimestamp, reshuffleByTimestampAndIndex, resolveSnapshotAuth, serializeSignature, setAuthorName, setAuthorWebsite, setGrant, setInitialState, setModelDescription, setModelExtension, setModelId, setModelName, setModuleDescription, setModuleName, setName, setNameOperation, setOperationDescription, setOperationErrorCode, setOperationErrorDescription, setOperationErrorName, setOperationErrorTemplate, setOperationName, setOperationReducer, setOperationSchema, setOperationScope, setOperationTemplate, setPreferredEditor, setPreferredEditorOperation, setStateSchema, sign, skipHeaderOperations, sortMappedOperations, sortOperations, split, toTransportAction, undo, undoOperation, undoOperationV2, updateChangeLogItem, updateDocument, updateHeaderRevision, updateOperationExample, updateStateExample, validateHeader, validateInitialState, validateModule, validateModuleOperation, validateModules, validateOperationName, validateOperations, validateStateSchemaName, verify, verifyOperationSignature, writeFileBrowser };
3938
5083
 
3939
5084
  //# sourceMappingURL=index.js.map