@powerhousedao/shared 6.2.2-dev.3 → 6.2.2-dev.30

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 (101) hide show
  1. package/dist/clis/args/access-token.mjs +1 -1
  2. package/dist/clis/args/{common-C5n5ai5C.d.mts → common-B_LcTLHX.d.mts} +5 -2
  3. package/dist/clis/args/{common-C5n5ai5C.d.mts.map → common-B_LcTLHX.d.mts.map} +1 -1
  4. package/dist/clis/args/{common-dbsvksvf.mjs → common-CcYbXrBx.mjs} +7 -2
  5. package/dist/clis/args/common-CcYbXrBx.mjs.map +1 -0
  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 +9 -0
  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 +2 -2
  19. package/dist/clis/args/index.mjs +4 -4
  20. package/dist/clis/args/init.d.mts +1 -1
  21. package/dist/clis/args/init.mjs +1 -1
  22. package/dist/clis/args/inspect.mjs +1 -1
  23. package/dist/clis/args/install.mjs +1 -1
  24. package/dist/clis/args/list.mjs +1 -1
  25. package/dist/clis/args/login.mjs +1 -1
  26. package/dist/clis/args/migrate.mjs +1 -1
  27. package/dist/clis/args/publish.mjs +1 -1
  28. package/dist/clis/args/registry.mjs +1 -1
  29. package/dist/clis/args/service.mjs +1 -1
  30. package/dist/clis/args/switchboard.mjs +1 -1
  31. package/dist/clis/args/uninstall.mjs +1 -1
  32. package/dist/clis/args/unpublish.mjs +1 -1
  33. package/dist/clis/args/vetra.mjs +1 -1
  34. package/dist/clis/build-config.d.mts +4 -4
  35. package/dist/clis/build-config.d.mts.map +1 -1
  36. package/dist/clis/constants.d.mts +156 -49
  37. package/dist/clis/constants.d.mts.map +1 -1
  38. package/dist/clis/constants.mjs +6 -2
  39. package/dist/clis/constants.mjs.map +1 -1
  40. package/dist/clis/index.d.mts +423 -5
  41. package/dist/clis/index.d.mts.map +1 -1
  42. package/dist/clis/index.mjs +258 -3
  43. package/dist/clis/index.mjs.map +1 -1
  44. package/dist/connect/config-loader.d.ts +2 -1
  45. package/dist/connect/config-loader.d.ts.map +1 -1
  46. package/dist/connect/index.d.ts +399 -2
  47. package/dist/connect/index.d.ts.map +1 -1
  48. package/dist/connect/index.js +465 -1
  49. package/dist/connect/index.js.map +1 -1
  50. package/dist/connect/json-adapter.d.ts.map +1 -1
  51. package/dist/{constants-C_EQX4DY.d.ts → constants-BP_gjn8g.d.ts} +1 -1
  52. package/dist/constants-BP_gjn8g.d.ts.map +1 -0
  53. package/dist/constants.d.ts +1 -1
  54. package/dist/document-drive/index.d.ts +2 -2
  55. package/dist/document-drive/index.d.ts.map +1 -1
  56. package/dist/document-model/index.d.ts +5 -5
  57. package/dist/document-model/index.js +737 -123
  58. package/dist/document-model/index.js.map +1 -1
  59. package/dist/document-model/mock.d.ts +1 -1
  60. package/dist/document-model/mock.js +32 -3
  61. package/dist/document-model/mock.js.map +1 -1
  62. package/dist/document-model/utils.d.ts +2 -2
  63. package/dist/document-model/utils.js +1 -1
  64. package/dist/{index-CQDIrK1k.d.ts → index-BJU79_T5.d.ts} +1 -1
  65. package/dist/index-BJU79_T5.d.ts.map +1 -0
  66. package/dist/{index-DLx4nU83.d.ts → index-OItp9eXf.d.ts} +205 -3
  67. package/dist/index-OItp9eXf.d.ts.map +1 -0
  68. package/dist/index.d.ts +5 -6
  69. package/dist/mock-BcFWPQyK.d.ts +22 -0
  70. package/dist/mock-BcFWPQyK.d.ts.map +1 -0
  71. package/dist/processors/index.d.ts +1 -1
  72. package/dist/registry/index.d.ts +5 -4
  73. package/dist/registry/index.d.ts.map +1 -1
  74. package/dist/registry/index.js +5 -4
  75. package/dist/registry/index.js.map +1 -1
  76. package/dist/registry/manifest-slim.d.ts +1 -1
  77. package/dist/registry/manifest-slim.d.ts.map +1 -1
  78. package/dist/registry/urls.d.ts +11 -0
  79. package/dist/registry/urls.d.ts.map +1 -0
  80. package/dist/registry/urls.js +15 -0
  81. package/dist/registry/urls.js.map +1 -0
  82. package/dist/{types-CgGSyOl6.d.ts → types-C7IdvgpK.d.ts} +32 -3
  83. package/dist/{types-CgGSyOl6.d.ts.map → types-C7IdvgpK.d.ts.map} +1 -1
  84. package/dist/{types-Bo4Rb8Yf.d.ts → types-aWKQyxzX.d.ts} +400 -12
  85. package/dist/types-aWKQyxzX.d.ts.map +1 -0
  86. package/dist/{utils-BEByNOHo.d.ts → utils-1EXU6Qr1.d.ts} +1 -1
  87. package/dist/utils-1EXU6Qr1.d.ts.map +1 -0
  88. package/dist/{utils-DKOFCM0Q.js → utils-CTt1XRn-.js} +36 -2
  89. package/dist/utils-CTt1XRn-.js.map +1 -0
  90. package/package.json +1 -1
  91. package/dist/clis/args/common-dbsvksvf.mjs.map +0 -1
  92. package/dist/constants-C_EQX4DY.d.ts.map +0 -1
  93. package/dist/index-CQDIrK1k.d.ts.map +0 -1
  94. package/dist/index-DLx4nU83.d.ts.map +0 -1
  95. package/dist/mock-CBcf78ra.d.ts +0 -7
  96. package/dist/mock-CBcf78ra.d.ts.map +0 -1
  97. package/dist/types-Bo4Rb8Yf.d.ts.map +0 -1
  98. package/dist/types-D0NNBVGA.d.ts +0 -167
  99. package/dist/types-D0NNBVGA.d.ts.map +0 -1
  100. package/dist/utils-BEByNOHo.d.ts.map +0 -1
  101. package/dist/utils-DKOFCM0Q.js.map +0 -1
@@ -1,4 +1,4 @@
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";
@@ -39,6 +39,75 @@ var DowngradeNotSupportedError = class extends Error {
39
39
  this.toVersion = toVersion;
40
40
  }
41
41
  };
42
+ /**
43
+ * Thrown when INITIALIZE_AUTH is applied to an already-initialized auth scope.
44
+ * The genesis action is valid only at auth revision zero.
45
+ */
46
+ var AuthAlreadyInitializedError = class extends Error {
47
+ documentId;
48
+ constructor(documentId) {
49
+ super(`Auth scope already initialized for document ${documentId}: INITIALIZE_AUTH is valid only at auth revision zero`);
50
+ this.name = "AuthAlreadyInitializedError";
51
+ this.documentId = documentId;
52
+ }
53
+ };
54
+ /**
55
+ * Thrown when INITIALIZE_AUTH is not signed by the document creator (its signer
56
+ * does not match `header.sig.publicKey`), so it cannot set the auth policy.
57
+ */
58
+ var AuthInitializerNotCreatorError = class extends Error {
59
+ documentId;
60
+ constructor(documentId) {
61
+ super(`INITIALIZE_AUTH for document ${documentId} must be signed by the document creator`);
62
+ this.name = "AuthInitializerNotCreatorError";
63
+ this.documentId = documentId;
64
+ }
65
+ };
66
+ /**
67
+ * Thrown when INITIALIZE_AUTH carries a version below 1. Version 0 is reserved
68
+ * for the uninitialized auth scope.
69
+ */
70
+ var InvalidAuthVersionError = class extends Error {
71
+ documentId;
72
+ version;
73
+ constructor(documentId, version) {
74
+ super(`Invalid auth policy version ${version} for document ${documentId}: INITIALIZE_AUTH requires an integer version >= 1`);
75
+ this.name = "InvalidAuthVersionError";
76
+ this.documentId = documentId;
77
+ this.version = version;
78
+ }
79
+ };
80
+ /** Thrown when a duplicate would lose the source policy's version or creator binding. */
81
+ var AuthPolicyNotPreservedError = class extends Error {
82
+ documentId;
83
+ constructor(documentId) {
84
+ super(`Duplicating document ${documentId} would not preserve its auth policy: the copy loses the policy version or its creator binding`);
85
+ this.name = "AuthPolicyNotPreservedError";
86
+ this.documentId = documentId;
87
+ }
88
+ };
89
+ /**
90
+ * Thrown when a grant referenced by REMOVE_GRANT or MOVE_GRANT does not exist.
91
+ */
92
+ var GrantNotFoundError = class extends Error {
93
+ grantId;
94
+ constructor(grantId) {
95
+ super(`Grant not found in auth scope: ${grantId}`);
96
+ this.name = "GrantNotFoundError";
97
+ this.grantId = grantId;
98
+ }
99
+ };
100
+ /**
101
+ * Thrown when a disallowed action (UNDO, REDO, PRUNE) targets the auth scope.
102
+ */
103
+ var AuthActionNotAllowedError = class extends Error {
104
+ actionType;
105
+ constructor(actionType) {
106
+ super(`${actionType} is not permitted on the auth scope`);
107
+ this.name = "AuthActionNotAllowedError";
108
+ this.actionType = actionType;
109
+ }
110
+ };
42
111
  var HashMismatchError = class extends Error {
43
112
  _scope;
44
113
  _document;
@@ -553,17 +622,102 @@ const ConfigEntrySchema = z.object({
553
622
  required: z.boolean().optional(),
554
623
  default: z.boolean().optional()
555
624
  });
625
+ const PwaUrlPatternSchema = z.union([z.string(), z.strictObject({
626
+ source: z.string(),
627
+ flags: z.string().optional()
628
+ }).refine((p) => {
629
+ try {
630
+ new RegExp(p.source, p.flags);
631
+ return true;
632
+ } catch {
633
+ return false;
634
+ }
635
+ }, { message: "source/flags do not compile to a valid RegExp" })]);
636
+ const PwaRuntimeCachingSchema = z.strictObject({
637
+ urlPattern: PwaUrlPatternSchema,
638
+ handler: z.enum([
639
+ "CacheFirst",
640
+ "CacheOnly",
641
+ "NetworkFirst",
642
+ "NetworkOnly",
643
+ "StaleWhileRevalidate"
644
+ ]),
645
+ method: z.enum([
646
+ "GET",
647
+ "POST",
648
+ "PUT",
649
+ "DELETE",
650
+ "HEAD",
651
+ "PATCH"
652
+ ]).optional(),
653
+ options: z.strictObject({
654
+ cacheName: z.string().optional(),
655
+ networkTimeoutSeconds: z.number().optional(),
656
+ expiration: z.strictObject({
657
+ maxEntries: z.number().optional(),
658
+ maxAgeSeconds: z.number().optional()
659
+ }).optional(),
660
+ cacheableResponse: z.strictObject({
661
+ statuses: z.array(z.number()).optional(),
662
+ headers: z.record(z.string(), z.string()).optional()
663
+ }).optional()
664
+ }).optional()
665
+ });
666
+ const PwaIconSchema = z.strictObject({
667
+ src: z.string(),
668
+ sizes: z.string().optional(),
669
+ type: z.string().optional(),
670
+ purpose: z.string().optional()
671
+ });
672
+ const PwaFileHandlerSchema = z.strictObject({
673
+ accept: z.record(z.string(), z.array(z.string().regex(/^\./, "file extensions must start with '.'"))),
674
+ icons: z.array(PwaIconSchema).optional(),
675
+ launch_type: z.enum(["single-client", "multiple-clients"]).optional()
676
+ });
677
+ const PwaManifestOverrideSchema = z.strictObject({
678
+ name: z.string().optional(),
679
+ short_name: z.string().optional(),
680
+ description: z.string().optional(),
681
+ theme_color: z.string().optional(),
682
+ background_color: z.string().optional(),
683
+ display: z.enum([
684
+ "fullscreen",
685
+ "standalone",
686
+ "minimal-ui",
687
+ "browser"
688
+ ]).optional(),
689
+ start_url: z.string().optional(),
690
+ scope: z.string().optional(),
691
+ icons: z.array(PwaIconSchema).optional(),
692
+ file_handlers: z.array(PwaFileHandlerSchema).optional(),
693
+ launch_handler: z.strictObject({ client_mode: z.enum([
694
+ "auto",
695
+ "focus-existing",
696
+ "navigate-existing",
697
+ "navigate-new"
698
+ ]) }).optional()
699
+ });
700
+ const PwaConfigSchema = z.strictObject({
701
+ manifest: PwaManifestOverrideSchema.optional(),
702
+ globPatterns: z.array(z.string()).optional(),
703
+ globIgnores: z.array(z.string()).optional(),
704
+ maximumFileSizeToCacheInBytes: z.number().optional(),
705
+ runtimeCaching: z.array(PwaRuntimeCachingSchema).optional(),
706
+ navigateFallbackDenylist: z.array(PwaUrlPatternSchema).optional()
707
+ });
556
708
  const ManifestSchema = z.object({
557
709
  name: z.string(),
558
710
  description: z.string().optional(),
559
711
  category: z.string().optional(),
712
+ image: z.string().optional(),
560
713
  publisher: PublisherSchema.optional(),
561
714
  documentModels: PowerhouseModulesSchema,
562
715
  apps: PowerhouseModulesSchema,
563
716
  editors: PowerhouseModulesSchema,
564
717
  processors: PowerhouseModulesSchema,
565
718
  subgraphs: PowerhouseModulesSchema,
566
- config: z.array(ConfigEntrySchema).optional()
719
+ config: z.array(ConfigEntrySchema).optional(),
720
+ pwa: PwaConfigSchema.optional()
567
721
  });
568
722
  //#endregion
569
723
  //#region document-model/actions.ts
@@ -849,6 +1003,231 @@ const actions = {
849
1003
  ...documentModelActions
850
1004
  };
851
1005
  //#endregion
1006
+ //#region document-model/document-type.ts
1007
+ const documentModelDocumentType = "powerhouse/document-model";
1008
+ const groupDocumentType = "@powerhousedao/document-group";
1009
+ //#endregion
1010
+ //#region document-model/auth-v1.ts
1011
+ /** Maximum number of grants in a policy. */
1012
+ const MAX_AUTH_GRANTS = 100;
1013
+ /** Maximum nesting depth of a condition tree. */
1014
+ const MAX_CONDITION_DEPTH = 10;
1015
+ /** Maximum node count (conditions plus operands) of a condition tree. */
1016
+ const MAX_CONDITION_NODES = 100;
1017
+ /** Maximum entries in an execute capability's operation list. */
1018
+ const MAX_CAPABILITY_OPERATIONS = 100;
1019
+ /**
1020
+ * Thrown when a grant violates the v1 validation rules. The message is stored
1021
+ * on error operations, so it must be a pure function of the input.
1022
+ */
1023
+ var InvalidGrantError = class extends Error {
1024
+ grantId;
1025
+ constructor(grantId, problem) {
1026
+ super(`Invalid grant "${grantId}": ${problem}`);
1027
+ this.name = "InvalidGrantError";
1028
+ this.grantId = grantId;
1029
+ }
1030
+ };
1031
+ /** Thrown for a `{ group }` principal on a group document: references never chain. */
1032
+ var GroupPrincipalNotAllowedError = class extends Error {
1033
+ grantId;
1034
+ constructor(grantId) {
1035
+ super(`Grant "${grantId}" uses a group principal on a group document: a group's auth scope cannot reference other groups`);
1036
+ this.name = "GroupPrincipalNotAllowedError";
1037
+ this.grantId = grantId;
1038
+ }
1039
+ };
1040
+ const GRANT_KEYS = new Set([
1041
+ "id",
1042
+ "description",
1043
+ "effect",
1044
+ "principal",
1045
+ "capability",
1046
+ "where"
1047
+ ]);
1048
+ const PRINCIPAL_KINDS = new Set([
1049
+ "anyone",
1050
+ "address",
1051
+ "group",
1052
+ "match"
1053
+ ]);
1054
+ const COMPARISON_CONDITION_KINDS = new Set([
1055
+ "eq",
1056
+ "ne",
1057
+ "lt",
1058
+ "lte",
1059
+ "gt",
1060
+ "gte"
1061
+ ]);
1062
+ function isPlainValue(value) {
1063
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1064
+ }
1065
+ function operandProblem(value, capabilityScope, budget) {
1066
+ budget.nodes -= 1;
1067
+ if (budget.nodes < 0) return `condition exceeds 100 nodes`;
1068
+ if (!isPlainValue(value)) return "operand must be an object";
1069
+ const keys = Object.keys(value);
1070
+ if (keys.length !== 1) return "operand must have exactly one of attr or lit";
1071
+ if (keys[0] === "attr") {
1072
+ const attr = value.attr;
1073
+ if (typeof attr !== "string" || attr.length === 0) return "attr must be a non-empty string";
1074
+ if (capabilityScope !== void 0 && capabilityScope !== "*" && attr.startsWith("doc.")) {
1075
+ const pathScope = attr.split(".")[1] ?? "";
1076
+ if (pathScope !== capabilityScope) return `condition path "${attr}" reads scope "${pathScope}" but the capability covers only scope "${capabilityScope}"`;
1077
+ }
1078
+ return null;
1079
+ }
1080
+ if (keys[0] === "lit") {
1081
+ const lit = value.lit;
1082
+ if (lit !== null && typeof lit !== "string" && typeof lit !== "number" && typeof lit !== "boolean") return "lit must be a string, number, boolean, or null";
1083
+ if (typeof lit === "number" && !Number.isFinite(lit)) return "lit must be a finite number";
1084
+ if (typeof lit === "number" && Object.is(lit, -0)) return "lit must not be negative zero";
1085
+ return null;
1086
+ }
1087
+ return `unknown operand kind "${keys[0]}"`;
1088
+ }
1089
+ function conditionProblem(value, capabilityScope, depth, budget) {
1090
+ if (depth > 10) return `condition exceeds depth 10`;
1091
+ budget.nodes -= 1;
1092
+ if (budget.nodes < 0) return `condition exceeds 100 nodes`;
1093
+ if (!isPlainValue(value)) return "condition must be an object";
1094
+ const keys = Object.keys(value);
1095
+ if (keys.length !== 1) return "condition must have exactly one operator";
1096
+ const kind = keys[0];
1097
+ const body = value[kind];
1098
+ if (COMPARISON_CONDITION_KINDS.has(kind)) {
1099
+ if (!Array.isArray(body) || body.length !== 2) return `${kind} requires a pair of operands`;
1100
+ for (const operand of body) {
1101
+ const problem = operandProblem(operand, capabilityScope, budget);
1102
+ if (problem !== null) return problem;
1103
+ }
1104
+ return null;
1105
+ }
1106
+ if (kind === "in" || kind === "notIn") {
1107
+ if (!Array.isArray(body) || body.length !== 2 || !Array.isArray(body[1])) return `${kind} requires an operand and an operand list`;
1108
+ const first = operandProblem(body[0], capabilityScope, budget);
1109
+ if (first !== null) return first;
1110
+ for (const operand of body[1]) {
1111
+ const problem = operandProblem(operand, capabilityScope, budget);
1112
+ if (problem !== null) return problem;
1113
+ }
1114
+ return null;
1115
+ }
1116
+ if (kind === "exists") return operandProblem(body, capabilityScope, budget);
1117
+ if (kind === "and" || kind === "or") {
1118
+ if (!Array.isArray(body)) return `${kind} requires a condition list`;
1119
+ for (const child of body) {
1120
+ const problem = conditionProblem(child, capabilityScope, depth + 1, budget);
1121
+ if (problem !== null) return problem;
1122
+ }
1123
+ return null;
1124
+ }
1125
+ if (kind === "not") return conditionProblem(body, capabilityScope, depth + 1, budget);
1126
+ return `unknown condition operator "${kind}"`;
1127
+ }
1128
+ function principalProblem(value, capabilityScope) {
1129
+ if (!isPlainValue(value)) return "principal must be an object";
1130
+ const keys = Object.keys(value);
1131
+ if (keys.length !== 1 || !PRINCIPAL_KINDS.has(keys[0])) return "principal must have exactly one of anyone, address, group, or match";
1132
+ const kind = keys[0];
1133
+ if (kind === "anyone" && value.anyone !== true) return "anyone must be true";
1134
+ if (kind === "address") {
1135
+ const address = value.address;
1136
+ if (typeof address !== "string" || address.length === 0) return "address must be a non-empty string";
1137
+ }
1138
+ if (kind === "group") {
1139
+ const group = value.group;
1140
+ if (typeof group !== "string" || group.length === 0) return "group must be a non-empty string";
1141
+ }
1142
+ if (kind === "match") return conditionProblem(value.match, capabilityScope, 1, { nodes: 100 });
1143
+ return null;
1144
+ }
1145
+ function capabilityProblem(value) {
1146
+ if (!isPlainValue(value)) return "capability must be an object";
1147
+ const can = value.can;
1148
+ if (can !== "read" && can !== "execute") return "capability.can must be read or execute";
1149
+ const allowedKeys = can === "execute" ? [
1150
+ "can",
1151
+ "scope",
1152
+ "operation"
1153
+ ] : ["can", "scope"];
1154
+ const unknownKeys = Object.keys(value).filter((key) => !allowedKeys.includes(key)).sort();
1155
+ if (unknownKeys.length > 0) return `unknown capability key "${unknownKeys[0]}"`;
1156
+ if (value.scope !== void 0) {
1157
+ if (typeof value.scope !== "string" || value.scope.length === 0) return "capability.scope must be a non-empty string";
1158
+ }
1159
+ if (can === "execute" && value.operation !== void 0) {
1160
+ const operation = value.operation;
1161
+ if (!Array.isArray(operation)) return "capability.operation must be an array";
1162
+ if (operation.length > 100) return `capability.operation exceeds 100 entries`;
1163
+ for (const entry of operation) if (typeof entry !== "string" || entry.length === 0) return "capability.operation entries must be non-empty strings";
1164
+ }
1165
+ return null;
1166
+ }
1167
+ /** Returns the first v1-rule violation, or null. Pure, total, deterministic. */
1168
+ function grantProblem(value) {
1169
+ if (!isPlainValue(value)) return "grant must be an object";
1170
+ const unknownKeys = Object.keys(value).filter((key) => !GRANT_KEYS.has(key)).sort();
1171
+ if (unknownKeys.length > 0) return `unknown grant key "${unknownKeys[0]}"`;
1172
+ if (typeof value.id !== "string" || value.id.length === 0) return "id must be a non-empty string";
1173
+ if (typeof value.description !== "string") return "description must be a string";
1174
+ if (value.effect !== "allow" && value.effect !== "deny") return "effect must be allow or deny";
1175
+ const capabilityValue = value.capability;
1176
+ const capability = capabilityProblem(capabilityValue);
1177
+ if (capability !== null) return capability;
1178
+ const capabilityScope = capabilityValue.scope;
1179
+ const principal = principalProblem(value.principal, capabilityScope);
1180
+ if (principal !== null) return principal;
1181
+ if (value.where !== void 0) return conditionProblem(value.where, capabilityScope, 1, { nodes: 100 });
1182
+ return null;
1183
+ }
1184
+ const GrantSchema = () => z.custom((value) => grantProblem(value) === null);
1185
+ /** V1 shape rules plus the group-document group-principal ban. */
1186
+ function assertValidGrant(grant, documentType) {
1187
+ const grantId = isPlainValue(grant) && typeof grant.id === "string" ? grant.id : "";
1188
+ const problem = grantProblem(grant);
1189
+ if (problem !== null) throw new InvalidGrantError(grantId, problem);
1190
+ if (documentType === "@powerhousedao/document-group" && "group" in grant.principal) throw new GroupPrincipalNotAllowedError(grantId);
1191
+ }
1192
+ /** Validates an initial grant list: the count cap plus every grant. */
1193
+ function assertValidInitialGrants(grants, documentType) {
1194
+ if (grants.length > 100) throw new InvalidGrantError("", `policy exceeds 100 grants`);
1195
+ for (const grant of grants) assertValidGrant(grant, documentType);
1196
+ }
1197
+ /** Validates a grant upsert: the grant itself plus the count cap on append. */
1198
+ function assertValidGrantUpsert(grant, existing, documentType) {
1199
+ assertValidGrant(grant, documentType);
1200
+ if (!existing.some((g) => g.id === grant.id) && existing.length >= 100) throw new InvalidGrantError(grant.id, `policy exceeds 100 grants`);
1201
+ }
1202
+ function capabilityCovers(capability, request) {
1203
+ if (capability.can !== request.verb) return false;
1204
+ const scope = capability.scope;
1205
+ if (scope !== void 0 && scope !== "*" && scope !== request.scope) return false;
1206
+ if (capability.can === "execute") {
1207
+ if (capability.operation === void 0) return true;
1208
+ return request.operation !== void 0 && capability.operation.includes(request.operation);
1209
+ }
1210
+ return true;
1211
+ }
1212
+ function principalMatches(principal, subject) {
1213
+ if ("anyone" in principal) return true;
1214
+ if ("address" in principal) return subject.address !== void 0 && subject.address.toLowerCase() === principal.address.toLowerCase();
1215
+ return false;
1216
+ }
1217
+ /**
1218
+ * Evaluates a v1 grant stack: default deny, last applicable grant wins.
1219
+ * Group and match principals and `where` conditions are not evaluated yet; a
1220
+ * grant that uses any of them never applies.
1221
+ */
1222
+ function evaluateGrants(grants, subject, request) {
1223
+ let decision = "deny";
1224
+ for (const grant of grants) {
1225
+ if (grant.where !== void 0) continue;
1226
+ if (capabilityCovers(grant.capability, request) && principalMatches(grant.principal, subject)) decision = grant.effect;
1227
+ }
1228
+ return decision;
1229
+ }
1230
+ //#endregion
852
1231
  //#region document-model/constants.ts
853
1232
  const documentModelFileExtension = "phdm";
854
1233
  const documentModelInitialLocalState = {};
@@ -1435,8 +1814,300 @@ const HASH_ALGORITHM_SHA512 = "sha512";
1435
1814
  const HASH_ENCODING_BASE64 = "base64";
1436
1815
  const HASH_ENCODING_HEX = "hex";
1437
1816
  //#endregion
1438
- //#region document-model/document-type.ts
1439
- const documentModelDocumentType = "powerhouse/document-model";
1817
+ //#region document-model/state.ts
1818
+ /**
1819
+ * Creates a default PHAuthState
1820
+ */
1821
+ function defaultAuthState() {
1822
+ return {
1823
+ version: 0,
1824
+ grants: []
1825
+ };
1826
+ }
1827
+ /**
1828
+ * Creates a default PHDocumentState
1829
+ */
1830
+ function defaultDocumentState() {
1831
+ return {
1832
+ version: 0,
1833
+ hash: {
1834
+ algorithm: HASH_ALGORITHM_SHA1,
1835
+ encoding: HASH_ENCODING_BASE64
1836
+ }
1837
+ };
1838
+ }
1839
+ /**
1840
+ * Creates a default PHBaseState with auth and document properties
1841
+ */
1842
+ function defaultBaseState() {
1843
+ return {
1844
+ auth: defaultAuthState(),
1845
+ document: defaultDocumentState()
1846
+ };
1847
+ }
1848
+ /**
1849
+ * Creates a PHAuthState with the given properties
1850
+ */
1851
+ function createAuthState(auth) {
1852
+ return {
1853
+ ...defaultAuthState(),
1854
+ ...auth
1855
+ };
1856
+ }
1857
+ /**
1858
+ * Creates a PHDocumentState with the given properties
1859
+ */
1860
+ function createDocumentState(document) {
1861
+ return {
1862
+ ...defaultDocumentState(),
1863
+ ...document
1864
+ };
1865
+ }
1866
+ /**
1867
+ * Creates a PHBaseState with the given auth and document properties
1868
+ */
1869
+ function createBaseState(auth, document) {
1870
+ return {
1871
+ auth: createAuthState(auth),
1872
+ document: createDocumentState(document)
1873
+ };
1874
+ }
1875
+ /**
1876
+ * Backfills the auth scope to the default for legacy documents serialized with
1877
+ * an empty `auth`. Replaces only `state.auth`. Idempotent.
1878
+ */
1879
+ function backfillAuthState(state) {
1880
+ return {
1881
+ ...state,
1882
+ auth: createAuthState(state.auth)
1883
+ };
1884
+ }
1885
+ function defaultGlobalState() {
1886
+ return {
1887
+ ...defaultBaseState(),
1888
+ author: {
1889
+ name: "",
1890
+ website: ""
1891
+ },
1892
+ description: "",
1893
+ extension: "",
1894
+ id: "",
1895
+ name: "",
1896
+ specifications: []
1897
+ };
1898
+ }
1899
+ function defaultLocalState() {
1900
+ return {};
1901
+ }
1902
+ function defaultPHState() {
1903
+ return {
1904
+ ...defaultBaseState(),
1905
+ global: defaultGlobalState(),
1906
+ local: defaultLocalState()
1907
+ };
1908
+ }
1909
+ function createGlobalState(state) {
1910
+ return {
1911
+ ...defaultGlobalState(),
1912
+ ...state || {}
1913
+ };
1914
+ }
1915
+ function createLocalState(state) {
1916
+ return {
1917
+ ...defaultLocalState(),
1918
+ ...state || {}
1919
+ };
1920
+ }
1921
+ function createState(baseState, globalState, localState) {
1922
+ return {
1923
+ ...createBaseState(baseState?.auth, baseState?.document),
1924
+ global: createGlobalState(globalState),
1925
+ local: createLocalState(localState)
1926
+ };
1927
+ }
1928
+ //#endregion
1929
+ //#region document-model/auth.ts
1930
+ const AUTH_ACTION_TYPES = [
1931
+ "INITIALIZE_AUTH",
1932
+ "SET_GRANT",
1933
+ "REMOVE_GRANT",
1934
+ "MOVE_GRANT"
1935
+ ];
1936
+ function isAuthAction(action) {
1937
+ return AUTH_ACTION_TYPES.includes(action.type);
1938
+ }
1939
+ /** Highest known policy version; decide() fails closed above it. */
1940
+ const MAX_SUPPORTED_AUTH_VERSION = 1;
1941
+ const InitializeAuthActionInputSchema = () => z.object({
1942
+ version: z.number().int().min(1),
1943
+ grants: z.array(GrantSchema()).max(100)
1944
+ });
1945
+ const SetGrantActionInputSchema = () => z.object({ grant: GrantSchema() });
1946
+ const RemoveGrantActionInputSchema = () => z.object({ id: z.string() });
1947
+ const MoveGrantActionInputSchema = () => z.object({
1948
+ id: z.string(),
1949
+ index: z.number()
1950
+ });
1951
+ const initializeAuth = (input) => createAction("INITIALIZE_AUTH", input, void 0, InitializeAuthActionInputSchema, "auth");
1952
+ const setGrant = (input) => createAction("SET_GRANT", input, void 0, SetGrantActionInputSchema, "auth");
1953
+ const removeGrant = (input) => createAction("REMOVE_GRANT", input, void 0, RemoveGrantActionInputSchema, "auth");
1954
+ const moveGrant = (input) => createAction("MOVE_GRANT", input, void 0, MoveGrantActionInputSchema, "auth");
1955
+ /**
1956
+ * Destructuring a null input (reachable via raw synced operations) would
1957
+ * store an engine-specific TypeError message on the error operation.
1958
+ */
1959
+ function assertActionInputShape(input) {
1960
+ if (!isPlainValue(input)) throw new InvalidActionInputError({ input: "must be an object" });
1961
+ }
1962
+ function withGrants(document, grants) {
1963
+ return {
1964
+ ...document,
1965
+ state: {
1966
+ ...document.state,
1967
+ auth: {
1968
+ ...document.state.auth,
1969
+ grants
1970
+ }
1971
+ }
1972
+ };
1973
+ }
1974
+ const P256_PUBKEY_MULTICODEC = [128, 36];
1975
+ const DID_KEY_PREFIX = "did:key:z";
1976
+ function bytesEqual(a, b) {
1977
+ if (a.length !== b.length) return false;
1978
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
1979
+ return true;
1980
+ }
1981
+ /**
1982
+ * True when `signerKey` (an ActionSigner app key, a did:key) identifies the same
1983
+ * key recorded as the document creator. Returns false
1984
+ * when there is no creator (empty JWK) or no signer key.
1985
+ */
1986
+ function isDocumentCreator(creatorKey, signerKey) {
1987
+ if (!creatorKey?.x || !creatorKey.y) return false;
1988
+ if (!signerKey || !signerKey.startsWith(DID_KEY_PREFIX)) return false;
1989
+ const decoded = base58Decode(signerKey.slice(9));
1990
+ if (!decoded || decoded.length !== 35) return false;
1991
+ if (decoded[0] !== P256_PUBKEY_MULTICODEC[0] || decoded[1] !== P256_PUBKEY_MULTICODEC[1]) return false;
1992
+ const parityPrefix = decoded[2];
1993
+ if (parityPrefix !== 2 && parityPrefix !== 3) return false;
1994
+ const didX = decoded.subarray(3, 35);
1995
+ const jwkX = base64UrlToBytes(creatorKey.x);
1996
+ const jwkY = base64UrlToBytes(creatorKey.y);
1997
+ if (jwkX.length !== 32 || jwkY.length !== 32) return false;
1998
+ if (!bytesEqual(didX, jwkX)) return false;
1999
+ return (jwkY[31] & 1) === 1 === (parityPrefix === 3);
2000
+ }
2001
+ /**
2002
+ * Sets the initial policy. Valid only while the auth scope is uninitialized
2003
+ * (version 0). The input version is the policy language version and must be an
2004
+ * integer >= 1; 0 is reserved for the uninitialized state. On a signed-header
2005
+ * document it must be signed by the document creator (`header.sig.publicKey`).
2006
+ */
2007
+ function applyInitializeAuthAction(document, action) {
2008
+ assertActionInputShape(action.input);
2009
+ const { version, grants } = action.input;
2010
+ if (!Number.isInteger(version) || version < 1) throw new InvalidAuthVersionError(document.header.id, version);
2011
+ if (document.state.auth.version !== 0) throw new AuthAlreadyInitializedError(document.header.id);
2012
+ if (!Array.isArray(grants)) throw new InvalidActionInputError({ grants: "must be an array" });
2013
+ assertValidInitialGrants(grants, document.header.documentType);
2014
+ const creatorKey = document.header.sig.publicKey;
2015
+ const signerKey = action.context?.signer?.app.key;
2016
+ const hasCreator = Boolean(creatorKey.kty || creatorKey.x || creatorKey.y);
2017
+ if (hasCreator && !isDocumentCreator(creatorKey, signerKey)) throw new AuthInitializerNotCreatorError(document.header.id);
2018
+ const creator = hasCreator ? signerKey : void 0;
2019
+ return {
2020
+ ...document,
2021
+ state: {
2022
+ ...document.state,
2023
+ auth: createAuthState(creator ? {
2024
+ version,
2025
+ grants,
2026
+ creator
2027
+ } : {
2028
+ version,
2029
+ grants
2030
+ })
2031
+ }
2032
+ };
2033
+ }
2034
+ /** Upserts a grant by id: replaces in place if present, otherwise appends. */
2035
+ function applySetGrantAction(document, action) {
2036
+ assertActionInputShape(action.input);
2037
+ const { grant } = action.input;
2038
+ const grants = document.state.auth.grants;
2039
+ assertValidGrantUpsert(grant, grants, document.header.documentType);
2040
+ return withGrants(document, grants.some((g) => g.id === grant.id) ? grants.map((g) => g.id === grant.id ? grant : g) : [...grants, grant]);
2041
+ }
2042
+ /** Removes a grant by id; throws if the id is not present. */
2043
+ function applyRemoveGrantAction(document, action) {
2044
+ assertActionInputShape(action.input);
2045
+ const { id } = action.input;
2046
+ const grants = document.state.auth.grants;
2047
+ if (!grants.some((g) => g.id === id)) throw new GrantNotFoundError(id);
2048
+ return withGrants(document, grants.filter((g) => g.id !== id));
2049
+ }
2050
+ /**
2051
+ * Moves a grant by id to a new index. Order is load-bearing (the last
2052
+ * applicable grant wins), so the relative order of the other grants is kept.
2053
+ * The target index is clamped to the valid range; an unknown id throws.
2054
+ */
2055
+ function applyMoveGrantAction(document, action) {
2056
+ assertActionInputShape(action.input);
2057
+ const { id, index } = action.input;
2058
+ const grants = document.state.auth.grants;
2059
+ const from = grants.findIndex((g) => g.id === id);
2060
+ if (from === -1) throw new GrantNotFoundError(id);
2061
+ const next = [...grants];
2062
+ const [moved] = next.splice(from, 1);
2063
+ const to = Math.max(0, Math.min(index, next.length));
2064
+ next.splice(to, 0, moved);
2065
+ return withGrants(document, next);
2066
+ }
2067
+ /**
2068
+ * Dispatches an auth-scope action to its handler. This is the auth scope's
2069
+ * dedicated reducer: it is applied by the base reducer instead of the model
2070
+ * reducer, mirroring the document-scope platform handlers. Unknown types are a
2071
+ * no-op, matching the model-reducer default.
2072
+ */
2073
+ function applyAuthAction(document, action) {
2074
+ switch (action.type) {
2075
+ case "INITIALIZE_AUTH": return applyInitializeAuthAction(document, action);
2076
+ case "SET_GRANT": return applySetGrantAction(document, action);
2077
+ case "REMOVE_GRANT": return applyRemoveGrantAction(document, action);
2078
+ case "MOVE_GRANT": return applyMoveGrantAction(document, action);
2079
+ default: return document;
2080
+ }
2081
+ }
2082
+ /**
2083
+ * Because only creators can initialize auth scopes, we must verify that either
2084
+ * the document has no auth or the version and creator match.
2085
+ */
2086
+ function assertAuthPreservedOnDuplicate(documentId, source, duplicated) {
2087
+ if (!source || source.version === 0) return;
2088
+ if (duplicated === void 0 || duplicated.version !== source.version || duplicated.creator !== source.creator) throw new AuthPolicyNotPreservedError(documentId);
2089
+ }
2090
+ /** UNDO, REDO and PRUNE are rejected on the auth scope. */
2091
+ function assertAuthScopeActionAllowed(action) {
2092
+ if (action.scope === "auth" && [
2093
+ "UNDO",
2094
+ "REDO",
2095
+ "PRUNE"
2096
+ ].includes(action.type)) throw new AuthActionNotAllowedError(action.type);
2097
+ }
2098
+ /**
2099
+ * Evaluates the auth policy for a single request. Pure and deterministic.
2100
+ *
2101
+ * An uninitialized policy (version 0, absent auth state, or a legacy `{}`
2102
+ * auth scope serialized before PHAuthState had a version) leaves the document
2103
+ * open. Once a policy exists the default is deny, and grants stack in order.
2104
+ */
2105
+ function decide(auth, subject, request) {
2106
+ if (!auth || !auth.version) return "allow";
2107
+ if (request.verb === "execute" && request.scope === "auth" && subject.key !== void 0 && subject.key === auth.creator) return "allow";
2108
+ if (auth.version > 1) return "deny";
2109
+ return evaluateGrants(auth.grants, subject, request);
2110
+ }
1440
2111
  //#endregion
1441
2112
  //#region document-model/document-schema.ts
1442
2113
  const BaseDocumentHeaderSchema = z.object({
@@ -1709,6 +2380,7 @@ function createDocumentScopeOperations(header, state) {
1709
2380
  function baseCreateDocument(createState, initialState, documentType = "") {
1710
2381
  const state = createState(initialState);
1711
2382
  const header = createPresignedHeader(generateId(), documentType);
2383
+ header.protocolVersions = { "base-reducer": 2 };
1712
2384
  return {
1713
2385
  header,
1714
2386
  state,
@@ -1804,6 +2476,18 @@ function mapSkippedOperationsV2(operations) {
1804
2476
  * Uses the V2 model where consecutive NOOPs form chains.
1805
2477
  * Unlike V1 garbageCollect, this preserves ALL operations but marks which to apply.
1806
2478
  */
2479
+ /**
2480
+ * The base-reducer protocol version a document is written against. Every
2481
+ * document carries one, set from the CREATE_DOCUMENT input. A header without
2482
+ * one was built outside that path, and choosing a version on its behalf would
2483
+ * replay the document through a reducer it was not written for, so it is an
2484
+ * error rather than a default.
2485
+ */
2486
+ function baseReducerVersion(header) {
2487
+ const version = header.protocolVersions?.["base-reducer"];
2488
+ if (typeof version !== "number") throw new Error(`Document ${header.id} carries no base-reducer protocol version`);
2489
+ return version;
2490
+ }
1807
2491
  function garbageCollectV2(sortedOperations) {
1808
2492
  const result = [];
1809
2493
  let noopChainLength = 0;
@@ -1825,7 +2509,8 @@ const defaultCreateState = (state) => {
1825
2509
  };
1826
2510
  function replayDocument(initialState, operations, reducer, header, dispatch, skipHeaderOperations = {}, options) {
1827
2511
  const { checkHashes = true, reuseOperationResultingState, operationResultingStateParser = parseResultingState, skipIndexValidation } = options || {};
1828
- let documentState = initialState;
2512
+ const backfilledInitialState = backfillAuthState(initialState);
2513
+ let documentState = backfilledInitialState;
1829
2514
  const operationsToReplay = [];
1830
2515
  const allScopes = new Set([
1831
2516
  ...Object.keys(operations),
@@ -1860,7 +2545,7 @@ function replayDocument(initialState, operations, reducer, header, dispatch, ski
1860
2545
  const document = {
1861
2546
  header,
1862
2547
  state: defaultCreateState(documentState),
1863
- initialState,
2548
+ initialState: backfilledInitialState,
1864
2549
  operations: initialOperations,
1865
2550
  clipboard: []
1866
2551
  };
@@ -2395,8 +3080,29 @@ function loadStateOperation(document, action) {
2395
3080
  ...document.header,
2396
3081
  name: action.state.name
2397
3082
  },
2398
- state: action.state.data
3083
+ state: backfillAuthState(action.state.data)
3084
+ };
3085
+ }
3086
+ /**
3087
+ * Reads an operation's outcome. A denial takes precedence over a reducer
3088
+ * error, since a denied operation never reaches its reducer.
3089
+ */
3090
+ function operationOutcome(operation) {
3091
+ if (operation.deniedReason !== void 0) return {
3092
+ kind: "denied",
3093
+ reason: operation.deniedReason
2399
3094
  };
3095
+ if (operation.error !== void 0) return {
3096
+ kind: "reducer-error",
3097
+ message: operation.error
3098
+ };
3099
+ return { kind: "applied" };
3100
+ }
3101
+ /**
3102
+ * True iff authorization rejected the action.
3103
+ */
3104
+ function isDenied(operation) {
3105
+ return operation.deniedReason !== void 0;
2400
3106
  }
2401
3107
  //#endregion
2402
3108
  //#region document-model/reducer.ts
@@ -2571,6 +3277,7 @@ function processUndoOperation(document, scope, customReducer, reuseOperationResu
2571
3277
  function baseReducer(document, action, customReducer, dispatch, options = {}) {
2572
3278
  const { skip, ignoreSkipOperations = false, reuseOperationResultingState = false, operationResultingStateParser, pruneOnSkip = true, branch = "main" } = options;
2573
3279
  let _action = actionFromAction(action);
3280
+ assertAuthScopeActionAllowed(_action);
2574
3281
  let skipValue = skip ?? options.replayOptions?.operation.skip ?? 0;
2575
3282
  let newDocument = { ...document };
2576
3283
  let reuseLastOperationIndex = false;
@@ -2618,6 +3325,13 @@ function baseReducer(document, action, customReducer, dispatch, options = {}) {
2618
3325
  }
2619
3326
  newDocument = create(newDocument, (draft) => {
2620
3327
  try {
3328
+ if (_action.scope === "auth") {
3329
+ const authState = applyAuthAction(newDocument, _action).state;
3330
+ unsafe(() => {
3331
+ draft.state = castDraft(authState);
3332
+ });
3333
+ return;
3334
+ }
2621
3335
  const newState = customReducer(draft.state, _action, dispatch);
2622
3336
  if (newState) unsafe(() => {
2623
3337
  draft.state = castDraft(newState);
@@ -3417,10 +4131,10 @@ function applyInitialState(document, action) {
3417
4131
  const input = action.input;
3418
4132
  const newState = input.initialState || input.state;
3419
4133
  if (newState) {
3420
- document.state = {
4134
+ document.state = backfillAuthState({
3421
4135
  ...document.state,
3422
4136
  ...newState
3423
- };
4137
+ });
3424
4138
  document.initialState = document.state;
3425
4139
  }
3426
4140
  }
@@ -3482,7 +4196,6 @@ function computeUpgradeTransitions(manifest, fromVersion, toVersion) {
3482
4196
  }
3483
4197
  //#endregion
3484
4198
  //#region document-model/versioned-replay.ts
3485
- const NON_DOMAIN_SCOPES$1 = new Set(["auth", "document"]);
3486
4199
  function highestReducerVersion(reducers) {
3487
4200
  const keys = Object.keys(reducers).map(Number);
3488
4201
  if (keys.length === 0) throw new Error("VersionedReplayConfig.reducers must not be empty");
@@ -3510,15 +4223,15 @@ function highestReducerVersion(reducers) {
3510
4223
  */
3511
4224
  function replayDocumentVersioned(initialState, operations, config, header, dispatch, options) {
3512
4225
  const { checkHashes = true, skipIndexValidation } = options || {};
3513
- const protocolVersion = header.protocolVersions?.["base-reducer"] ?? 1;
4226
+ const protocolVersion = baseReducerVersion(header);
3514
4227
  const spine = (operations["document"] ?? []).slice().sort((a, b) => a.index - b.index);
3515
4228
  const upgrades = spine.filter((op) => op.action.type === "UPGRADE_DOCUMENT");
3516
4229
  const legacyFallback = () => {
3517
- const domainOps = Object.fromEntries(Object.entries(operations).filter(([s]) => !NON_DOMAIN_SCOPES$1.has(s)));
4230
+ const replayOps = Object.fromEntries(Object.entries(operations).filter(([s]) => s !== "document"));
3518
4231
  const latestVersion = highestReducerVersion(config.reducers);
3519
4232
  const reducer = config.reducers[latestVersion];
3520
4233
  return {
3521
- ...replayDocument(initialState, domainOps, reducer, header, dispatch, {}, options),
4234
+ ...replayDocument(initialState, replayOps, reducer, header, dispatch, {}, options),
3522
4235
  operations
3523
4236
  };
3524
4237
  };
@@ -3542,14 +4255,14 @@ function replayDocumentVersioned(initialState, operations, config, header, dispa
3542
4255
  const a = op.action;
3543
4256
  return a.input.fromVersion > 0 && a.input.fromVersion < a.input.toVersion;
3544
4257
  });
3545
- const domainScopes = Object.keys(operations).filter((s) => !NON_DOMAIN_SCOPES$1.has(s));
4258
+ const replayScopes = Object.keys(operations).filter((s) => s !== "document");
3546
4259
  const scopeOps = {};
3547
- for (const s of domainScopes) scopeOps[s] = (operations[s] ?? []).slice().sort((a, b) => a.index - b.index);
4260
+ for (const s of replayScopes) scopeOps[s] = (operations[s] ?? []).slice().sort((a, b) => a.index - b.index);
3548
4261
  const boundaries = validatedUpgrades.map((upgradeOp) => {
3549
4262
  const revisionSnapshot = upgradeOp.action.input.revision;
3550
4263
  const upgradeTimestamp = upgradeOp.timestampUtcMs;
3551
4264
  const boundary = {};
3552
- for (const s of domainScopes) {
4265
+ for (const s of replayScopes) {
3553
4266
  const ops = scopeOps[s] ?? [];
3554
4267
  if (revisionSnapshot !== void 0) {
3555
4268
  const rev = revisionSnapshot[s] ?? 0;
@@ -3567,7 +4280,7 @@ function replayDocumentVersioned(initialState, operations, config, header, dispa
3567
4280
  }
3568
4281
  return boundary;
3569
4282
  });
3570
- for (let i = 1; i < boundaries.length; i++) for (const s of domainScopes) {
4283
+ for (let i = 1; i < boundaries.length; i++) for (const s of replayScopes) {
3571
4284
  const prev = boundaries[i - 1]?.[s] ?? 0;
3572
4285
  const curr = boundaries[i]?.[s] ?? 0;
3573
4286
  if (boundaries[i]) boundaries[i][s] = Math.max(prev, curr);
@@ -3579,10 +4292,11 @@ function replayDocumentVersioned(initialState, operations, config, header, dispa
3579
4292
  ]);
3580
4293
  const initialOperations = {};
3581
4294
  for (const s of allScopes) initialOperations[s] = [];
4295
+ const backfilledSeed = backfillAuthState(seedState);
3582
4296
  let document = {
3583
4297
  header,
3584
- state: seedState,
3585
- initialState: seedState,
4298
+ state: backfilledSeed,
4299
+ initialState: backfilledSeed,
3586
4300
  operations: initialOperations,
3587
4301
  clipboard: []
3588
4302
  };
@@ -3594,7 +4308,7 @@ function replayDocumentVersioned(initialState, operations, config, header, dispa
3594
4308
  const available = Object.keys(config.reducers).join(", ");
3595
4309
  throw new Error(`No reducer registered for document version ${currentVersion}. Available versions: ${available}`);
3596
4310
  }
3597
- for (const s of domainScopes) {
4311
+ for (const s of replayScopes) {
3598
4312
  const ops = scopeOps[s] ?? [];
3599
4313
  const segStart = k === 0 ? 0 : boundaries[k - 1]?.[s] ?? 0;
3600
4314
  const segEnd = k < validatedUpgrades.length ? boundaries[k]?.[s] ?? ops.length : ops.length;
@@ -3647,7 +4361,7 @@ function replayDocumentVersioned(initialState, operations, config, header, dispa
3647
4361
  }
3648
4362
  };
3649
4363
  if (!checkHashes) {
3650
- const allReplayedOps = domainScopes.flatMap((s) => scopeOps[s] ?? []);
4364
+ const allReplayedOps = replayScopes.flatMap((s) => scopeOps[s] ?? []);
3651
4365
  for (const scope of Object.keys(document.state)) {
3652
4366
  const capturedHash = segmentEndHashPerScope.get(scope);
3653
4367
  const scopeHash = capturedHash !== void 0 ? capturedHash : hashDocumentStateForScope(document, scope);
@@ -3691,7 +4405,6 @@ function replayDocumentVersioned(initialState, operations, config, header, dispa
3691
4405
  }
3692
4406
  //#endregion
3693
4407
  //#region document-model/files.ts
3694
- const NON_DOMAIN_SCOPES = new Set(["auth", "document"]);
3695
4408
  function zipAsync(data) {
3696
4409
  return new Promise((resolve, reject) => {
3697
4410
  zip(data, (err, out) => err ? reject(err) : resolve(out));
@@ -3798,7 +4511,7 @@ async function parseZipData(data) {
3798
4511
  async function loadFromZipData(data, reducer, options) {
3799
4512
  const { initialState, header, clearedOperations } = await parseZipData(data);
3800
4513
  return {
3801
- ...replayDocument(initialState, Object.fromEntries(Object.entries(clearedOperations).filter(([scope]) => !NON_DOMAIN_SCOPES.has(scope))), reducer, header, void 0, {}, options),
4514
+ ...replayDocument(initialState, Object.fromEntries(Object.entries(clearedOperations).filter(([scope]) => scope !== "document")), reducer, header, void 0, {}, options),
3802
4515
  operations: clearedOperations
3803
4516
  };
3804
4517
  }
@@ -3834,105 +4547,6 @@ const getFileBrowser = (file) => {
3834
4547
  return Promise.resolve().then(() => readFileBrowser(file));
3835
4548
  };
3836
4549
  //#endregion
3837
- //#region document-model/state.ts
3838
- /**
3839
- * Creates a default PHAuthState
3840
- */
3841
- function defaultAuthState() {
3842
- return {};
3843
- }
3844
- /**
3845
- * Creates a default PHDocumentState
3846
- */
3847
- function defaultDocumentState() {
3848
- return {
3849
- version: 0,
3850
- hash: {
3851
- algorithm: HASH_ALGORITHM_SHA1,
3852
- encoding: HASH_ENCODING_BASE64
3853
- }
3854
- };
3855
- }
3856
- /**
3857
- * Creates a default PHBaseState with auth and document properties
3858
- */
3859
- function defaultBaseState() {
3860
- return {
3861
- auth: defaultAuthState(),
3862
- document: defaultDocumentState()
3863
- };
3864
- }
3865
- /**
3866
- * Creates a PHAuthState with the given properties
3867
- */
3868
- function createAuthState(auth) {
3869
- return {
3870
- ...defaultAuthState(),
3871
- ...auth
3872
- };
3873
- }
3874
- /**
3875
- * Creates a PHDocumentState with the given properties
3876
- */
3877
- function createDocumentState(document) {
3878
- return {
3879
- ...defaultDocumentState(),
3880
- ...document
3881
- };
3882
- }
3883
- /**
3884
- * Creates a PHBaseState with the given auth and document properties
3885
- */
3886
- function createBaseState(auth, document) {
3887
- return {
3888
- auth: createAuthState(auth),
3889
- document: createDocumentState(document)
3890
- };
3891
- }
3892
- function defaultGlobalState() {
3893
- return {
3894
- ...defaultBaseState(),
3895
- author: {
3896
- name: "",
3897
- website: ""
3898
- },
3899
- description: "",
3900
- extension: "",
3901
- id: "",
3902
- name: "",
3903
- specifications: []
3904
- };
3905
- }
3906
- function defaultLocalState() {
3907
- return {};
3908
- }
3909
- function defaultPHState() {
3910
- return {
3911
- ...defaultBaseState(),
3912
- global: defaultGlobalState(),
3913
- local: defaultLocalState()
3914
- };
3915
- }
3916
- function createGlobalState(state) {
3917
- return {
3918
- ...defaultGlobalState(),
3919
- ...state || {}
3920
- };
3921
- }
3922
- function createLocalState(state) {
3923
- return {
3924
- ...defaultLocalState(),
3925
- ...state || {}
3926
- };
3927
- }
3928
- function createState(baseState, globalState, localState) {
3929
- return {
3930
- ...createBaseState(baseState?.auth, baseState?.document),
3931
- global: createGlobalState(globalState),
3932
- local: createLocalState(localState)
3933
- };
3934
- }
3935
- //#endregion
3936
- 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 };
4550
+ export { AUTH_ACTION_TYPES, AddChangeLogItemInputSchema, AddModuleInputSchema, AddOperationErrorInputSchema, AddOperationExampleInputSchema, AddOperationInputSchema, AddStateExampleInputSchema, AuthActionNotAllowedError, AuthAlreadyInitializedError, AuthInitializerNotCreatorError, AuthPolicyNotPreservedError, AuthorSchema, BaseDocumentHeaderSchema, BaseDocumentStateSchema, CodeExampleSchema, ConfigEntrySchema, ConfigEntryTypeSchema, 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, UpdateChangeLogItemInputSchema, UpdateOperationExampleInputSchema, UpdateStateExampleInputSchema, ab2hex, actionContext, actionFromAction, actionSigner, actions, addChangeLogItem, addModule, addOperation, addOperationError, addOperationExample, addStateExample, addUndo, applyAuthAction, applyDeleteDocumentAction, applyInitializeAuthAction, applyMoveGrantAction, applyRemoveGrantAction, applySetGrantAction, applyUpgradeDocumentAction, 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, diffOperations, documentModelActions, documentModelDocumentType, documentModelFileExtension, documentModelGlobalState, documentModelHeaderReducer, documentModelInitialGlobalState, documentModelInitialLocalState, documentModelLoadFromInput, documentModelModuleReducer, documentModelOperationErrorReducer, documentModelOperationExampleReducer, documentModelOperationReducer, documentModelReducer, documentModelSaveToFileHandle, documentModelStateReducer, documentModelStateSchemaReducer, documentModelVersioningReducer, evaluateGrants, fetchFileBrowser, filterDocumentOperationsResultingState, filterDuplicatedOperations, findModuleOrThrow, findOperationErrorOrThrow, findOperationExampleOrThrow, findOperationOrThrow, garbageCollect, garbageCollectDocumentOperations, garbageCollectV2, generateId, generateMock, getAllOperationNames, getDocumentLastModified, getFileBrowser, getUnixTimestamp, grantProblem, groupDocumentType, groupOperationsByScope, hashBrowser, hashDocumentStateForScope, hex2ab, initializeAuth, isAuthAction, isDefinedNonNullAny, isDenied, isDocumentAction, isDocumentCreator, isDocumentModelDocument, isDocumentModelState, isNoopOperation, isPlainValue, isReservedOperationName, isUndo, isUndoRedo, isValidOperationNameFormat, loadState, loadStateOperation, mapSkippedOperations, mapSkippedOperationsV2, merge, moveGrant, moveOperation, nextSkipNumber, noop, operationExampleCreators, operationFromAction, operationFromOperation, operationOutcome, operationWithContext, operationsAreEqual, parseResultingState, precedes, prepareOperations, processUndoRedo, prune, pruneOperation, readFileBrowser, readOnly, redo, redoOperation, releaseNewVersion, removeExistingOperations, removeGrant, reorderChangeLogItems, reorderModuleOperations, reorderModules, reorderOperationErrors, reorderOperationExamples, reorderStateExamples, replayDocument, replayDocumentVersioned, replayOperations, reshuffleByTimestamp, reshuffleByTimestampAndIndex, 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, undo, undoOperation, undoOperationV2, updateChangeLogItem, updateDocument, updateHeaderRevision, updateOperationExample, updateStateExample, validateHeader, validateInitialState, validateModule, validateModuleOperation, validateModules, validateOperationName, validateOperations, validateStateSchemaName, verify, verifyOperationSignature, writeFileBrowser };
3937
4551
 
3938
4552
  //# sourceMappingURL=index.js.map