@peac/policy-kit 0.10.9 → 0.10.10

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.
package/dist/loader.js DELETED
@@ -1,245 +0,0 @@
1
- "use strict";
2
- /**
3
- * PEAC Policy Kit Loader
4
- *
5
- * Loads and validates policy documents from YAML or JSON.
6
- * No network calls - file system only.
7
- *
8
- * @packageDocumentation
9
- */
10
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
11
- if (k2 === undefined) k2 = k;
12
- var desc = Object.getOwnPropertyDescriptor(m, k);
13
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
14
- desc = { enumerable: true, get: function() { return m[k]; } };
15
- }
16
- Object.defineProperty(o, k2, desc);
17
- }) : (function(o, m, k, k2) {
18
- if (k2 === undefined) k2 = k;
19
- o[k2] = m[k];
20
- }));
21
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
22
- Object.defineProperty(o, "default", { enumerable: true, value: v });
23
- }) : function(o, v) {
24
- o["default"] = v;
25
- });
26
- var __importStar = (this && this.__importStar) || (function () {
27
- var ownKeys = function(o) {
28
- ownKeys = Object.getOwnPropertyNames || function (o) {
29
- var ar = [];
30
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
31
- return ar;
32
- };
33
- return ownKeys(o);
34
- };
35
- return function (mod) {
36
- if (mod && mod.__esModule) return mod;
37
- var result = {};
38
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
39
- __setModuleDefault(result, mod);
40
- return result;
41
- };
42
- })();
43
- Object.defineProperty(exports, "__esModule", { value: true });
44
- exports.PolicyValidationError = exports.PolicyLoadError = void 0;
45
- exports.parsePolicy = parsePolicy;
46
- exports.validatePolicy = validatePolicy;
47
- exports.loadPolicy = loadPolicy;
48
- exports.policyFileExists = policyFileExists;
49
- exports.createExamplePolicy = createExamplePolicy;
50
- exports.serializePolicyYaml = serializePolicyYaml;
51
- exports.serializePolicyJson = serializePolicyJson;
52
- const fs = __importStar(require("fs"));
53
- const path = __importStar(require("path"));
54
- const yaml = __importStar(require("yaml"));
55
- const zod_1 = require("zod");
56
- const types_1 = require("./types");
57
- /**
58
- * Policy load error
59
- */
60
- class PolicyLoadError extends Error {
61
- cause;
62
- constructor(message, cause) {
63
- super(message);
64
- this.cause = cause;
65
- this.name = 'PolicyLoadError';
66
- }
67
- }
68
- exports.PolicyLoadError = PolicyLoadError;
69
- /**
70
- * Policy validation error with details
71
- */
72
- class PolicyValidationError extends PolicyLoadError {
73
- issues;
74
- constructor(message, issues) {
75
- super(message);
76
- this.issues = issues;
77
- this.name = 'PolicyValidationError';
78
- }
79
- }
80
- exports.PolicyValidationError = PolicyValidationError;
81
- /**
82
- * Parse policy from string content
83
- *
84
- * @param content - YAML or JSON string
85
- * @param format - Optional format hint ('yaml' | 'json'), auto-detected if not provided
86
- * @returns Validated policy document
87
- * @throws PolicyLoadError on parse failure
88
- * @throws PolicyValidationError on schema validation failure
89
- */
90
- function parsePolicy(content, format) {
91
- let parsed;
92
- try {
93
- if (format === 'json') {
94
- parsed = JSON.parse(content);
95
- }
96
- else if (format === 'yaml') {
97
- parsed = yaml.parse(content);
98
- }
99
- else {
100
- // Auto-detect: try JSON first (faster), fall back to YAML
101
- try {
102
- parsed = JSON.parse(content);
103
- }
104
- catch {
105
- parsed = yaml.parse(content);
106
- }
107
- }
108
- }
109
- catch (err) {
110
- throw new PolicyLoadError(`Failed to parse policy: ${err instanceof Error ? err.message : String(err)}`, err instanceof Error ? err : undefined);
111
- }
112
- return validatePolicy(parsed);
113
- }
114
- /**
115
- * Validate a parsed policy object
116
- *
117
- * @param obj - Parsed policy object (from YAML/JSON)
118
- * @returns Validated policy document
119
- * @throws PolicyValidationError on schema validation failure
120
- */
121
- function validatePolicy(obj) {
122
- try {
123
- return types_1.PolicyDocumentSchema.parse(obj);
124
- }
125
- catch (err) {
126
- if (err instanceof zod_1.ZodError) {
127
- const issues = err.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join('; ');
128
- throw new PolicyValidationError(`Policy validation failed: ${issues}`, err.issues);
129
- }
130
- throw new PolicyLoadError(`Policy validation failed: ${err instanceof Error ? err.message : String(err)}`, err instanceof Error ? err : undefined);
131
- }
132
- }
133
- /**
134
- * Load policy from file
135
- *
136
- * @param filePath - Path to policy file (.yaml, .yml, or .json)
137
- * @returns Validated policy document
138
- * @throws PolicyLoadError on file read or parse failure
139
- * @throws PolicyValidationError on schema validation failure
140
- */
141
- function loadPolicy(filePath) {
142
- const ext = path.extname(filePath).toLowerCase();
143
- let format;
144
- if (ext === '.json') {
145
- format = 'json';
146
- }
147
- else if (ext === '.yaml' || ext === '.yml') {
148
- format = 'yaml';
149
- }
150
- let content;
151
- try {
152
- content = fs.readFileSync(filePath, 'utf-8');
153
- }
154
- catch (err) {
155
- throw new PolicyLoadError(`Failed to read policy file: ${err instanceof Error ? err.message : String(err)}`, err instanceof Error ? err : undefined);
156
- }
157
- return parsePolicy(content, format);
158
- }
159
- /**
160
- * Check if a policy file exists and is readable
161
- *
162
- * @param filePath - Path to policy file
163
- * @returns true if file exists and is readable
164
- */
165
- function policyFileExists(filePath) {
166
- try {
167
- fs.accessSync(filePath, fs.constants.R_OK);
168
- return true;
169
- }
170
- catch {
171
- return false;
172
- }
173
- }
174
- /**
175
- * Create a minimal example policy document
176
- *
177
- * Useful for scaffolding new policy files.
178
- */
179
- function createExamplePolicy() {
180
- return {
181
- version: types_1.POLICY_VERSION,
182
- name: 'Example Policy',
183
- defaults: {
184
- decision: 'deny',
185
- reason: 'No matching rule found',
186
- },
187
- rules: [
188
- {
189
- name: 'allow-subscribed-crawl',
190
- subject: {
191
- type: 'human',
192
- labels: ['subscribed'],
193
- },
194
- purpose: 'crawl',
195
- licensing_mode: 'subscription',
196
- decision: 'allow',
197
- reason: 'Subscribed users can crawl',
198
- },
199
- {
200
- name: 'allow-verified-agents-inference',
201
- subject: {
202
- type: 'agent',
203
- labels: ['verified'],
204
- },
205
- purpose: ['inference', 'ai_input'],
206
- licensing_mode: 'pay_per_inference',
207
- decision: 'allow',
208
- reason: 'Verified agents can run inference with payment',
209
- },
210
- {
211
- name: 'review-org-train',
212
- subject: {
213
- type: 'org',
214
- },
215
- purpose: 'train',
216
- decision: 'review',
217
- reason: 'Training requests from organizations require review',
218
- },
219
- ],
220
- };
221
- }
222
- /**
223
- * Serialize policy to YAML string
224
- *
225
- * @param policy - Policy document to serialize
226
- * @returns YAML string
227
- */
228
- function serializePolicyYaml(policy) {
229
- return yaml.stringify(policy, {
230
- lineWidth: 100,
231
- defaultKeyType: 'PLAIN',
232
- defaultStringType: 'QUOTE_DOUBLE',
233
- });
234
- }
235
- /**
236
- * Serialize policy to JSON string
237
- *
238
- * @param policy - Policy document to serialize
239
- * @param pretty - Pretty-print with indentation (default: true)
240
- * @returns JSON string
241
- */
242
- function serializePolicyJson(policy, pretty = true) {
243
- return JSON.stringify(policy, null, pretty ? 2 : undefined);
244
- }
245
- //# sourceMappingURL=loader.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"loader.js","sourceRoot":"","sources":["../src/loader.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CH,kCAwBC;AASD,wCAaC;AAUD,gCAqBC;AAQD,4CAOC;AAOD,kDA0CC;AAQD,kDAMC;AASD,kDAEC;AA/MD,uCAAyB;AACzB,2CAA6B;AAC7B,2CAA6B;AAC7B,6BAA+B;AAC/B,mCAA+E;AAE/E;;GAEG;AACH,MAAa,eAAgB,SAAQ,KAAK;IAGtB;IAFlB,YACE,OAAe,EACC,KAAwB;QAExC,KAAK,CAAC,OAAO,CAAC,CAAC;QAFC,UAAK,GAAL,KAAK,CAAmB;QAGxC,IAAI,CAAC,IAAI,GAAG,iBAAiB,CAAC;IAChC,CAAC;CACF;AARD,0CAQ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;iBACZ;gBACD,OAAO,EAAE,OAAO;gBAChB,QAAQ,EAAE,QAAQ;gBAClB,MAAM,EAAE,qDAAqD;aAC9D;SACF;KACF,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,SAAgB,mBAAmB,CAAC,MAAsB;IACxD,OAAO,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE;QAC5B,SAAS,EAAE,GAAG;QACd,cAAc,EAAE,OAAO;QACvB,iBAAiB,EAAE,cAAc;KAClC,CAAC,CAAC;AACL,CAAC;AAED;;;;;;GAMG;AACH,SAAgB,mBAAmB,CAAC,MAAsB,EAAE,MAAM,GAAG,IAAI;IACvE,OAAO,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;AAC9D,CAAC"}
package/dist/profiles.js DELETED
@@ -1,368 +0,0 @@
1
- "use strict";
2
- /**
3
- * Profile Loader API
4
- *
5
- * Convenience functions for working with pre-built policy profiles.
6
- *
7
- * @example
8
- * ```typescript
9
- * import { listProfiles, loadProfile, customizeProfile } from '@peac/policy-kit';
10
- *
11
- * // List available profiles
12
- * const ids = listProfiles(); // ['api-provider', 'news-media', ...]
13
- *
14
- * // Load a profile
15
- * const profile = loadProfile('news-media');
16
- *
17
- * // Customize with parameters
18
- * const policy = customizeProfile('news-media', {
19
- * contact: 'licensing@example.com',
20
- * rate_limit: '100/hour',
21
- * });
22
- * ```
23
- *
24
- * @packageDocumentation
25
- */
26
- Object.defineProperty(exports, "__esModule", { value: true });
27
- exports.ProfileError = void 0;
28
- exports.listProfiles = listProfiles;
29
- exports.hasProfile = hasProfile;
30
- exports.loadProfile = loadProfile;
31
- exports.getProfile = getProfile;
32
- exports.validateProfileParams = validateProfileParams;
33
- exports.customizeProfile = customizeProfile;
34
- exports.getAllProfiles = getAllProfiles;
35
- exports.getProfileSummary = getProfileSummary;
36
- const profiles_1 = require("./generated/profiles");
37
- const types_1 = require("./types");
38
- /**
39
- * Error thrown when profile operations fail
40
- */
41
- class ProfileError extends Error {
42
- code;
43
- constructor(message, code) {
44
- super(message);
45
- this.code = code;
46
- this.name = 'ProfileError';
47
- }
48
- }
49
- exports.ProfileError = ProfileError;
50
- /**
51
- * List all available profile IDs
52
- *
53
- * @returns Array of profile IDs
54
- *
55
- * @example
56
- * ```typescript
57
- * const ids = listProfiles();
58
- * // ['api-provider', 'news-media', 'open-source', 'saas-docs']
59
- * ```
60
- */
61
- function listProfiles() {
62
- return [...profiles_1.PROFILE_IDS];
63
- }
64
- /**
65
- * Check if a profile ID exists
66
- *
67
- * @param id - Profile ID to check
68
- * @returns true if profile exists
69
- *
70
- * @example
71
- * ```typescript
72
- * if (hasProfile('news-media')) {
73
- * const profile = loadProfile('news-media');
74
- * }
75
- * ```
76
- */
77
- function hasProfile(id) {
78
- return profiles_1.PROFILE_IDS.includes(id);
79
- }
80
- /**
81
- * Load a profile by ID
82
- *
83
- * @param id - Profile ID
84
- * @returns Profile definition
85
- * @throws ProfileError if profile not found
86
- *
87
- * @example
88
- * ```typescript
89
- * const profile = loadProfile('news-media');
90
- * console.log(profile.name); // 'News Media Publisher'
91
- * ```
92
- */
93
- function loadProfile(id) {
94
- const profile = profiles_1.PROFILES[id];
95
- if (!profile) {
96
- throw new ProfileError(`Profile not found: ${id}`, 'PROFILE_NOT_FOUND');
97
- }
98
- return profile;
99
- }
100
- /**
101
- * Get a profile by ID, returning undefined if not found
102
- *
103
- * @param id - Profile ID
104
- * @returns Profile definition or undefined
105
- *
106
- * @example
107
- * ```typescript
108
- * const profile = getProfile('news-media');
109
- * if (profile) {
110
- * console.log(profile.name);
111
- * }
112
- * ```
113
- */
114
- function getProfile(id) {
115
- if (!hasProfile(id)) {
116
- return undefined;
117
- }
118
- return profiles_1.PROFILES[id];
119
- }
120
- /**
121
- * Validate parameters against a profile's requirements
122
- *
123
- * @param profile - Profile definition or ID
124
- * @param params - Parameters to validate
125
- * @returns Validation result with errors and warnings
126
- *
127
- * @example
128
- * ```typescript
129
- * const result = validateProfileParams('news-media', {
130
- * contact: 'invalid-email',
131
- * });
132
- *
133
- * if (!result.valid) {
134
- * console.error(result.errors);
135
- * }
136
- * ```
137
- */
138
- function validateProfileParams(profile, params) {
139
- const def = typeof profile === 'string' ? loadProfile(profile) : profile;
140
- const errors = [];
141
- const warnings = [];
142
- const paramDefs = def.parameters || {};
143
- const providedKeys = new Set(Object.keys(params));
144
- // Check for required parameters
145
- for (const [key, paramDef] of Object.entries(paramDefs)) {
146
- if (paramDef.required && !providedKeys.has(key)) {
147
- errors.push({
148
- parameter: key,
149
- message: `Required parameter missing: ${key}`,
150
- code: 'MISSING_REQUIRED',
151
- });
152
- }
153
- }
154
- // Validate provided parameters
155
- for (const [key, value] of Object.entries(params)) {
156
- const paramDef = paramDefs[key];
157
- if (!paramDef) {
158
- errors.push({
159
- parameter: key,
160
- message: `Unknown parameter: ${key}`,
161
- code: 'UNKNOWN_PARAMETER',
162
- });
163
- continue;
164
- }
165
- // Skip validation if value is undefined/null
166
- if (value === undefined || value === null) {
167
- if (paramDef.required) {
168
- errors.push({
169
- parameter: key,
170
- message: `Required parameter is null/undefined: ${key}`,
171
- code: 'MISSING_REQUIRED',
172
- });
173
- }
174
- continue;
175
- }
176
- // Type-specific validation
177
- const strValue = String(value);
178
- const validationError = validateParameterValue(key, strValue, paramDef);
179
- if (validationError) {
180
- errors.push(validationError);
181
- }
182
- }
183
- return {
184
- valid: errors.length === 0,
185
- errors,
186
- warnings,
187
- };
188
- }
189
- /**
190
- * Validate a single parameter value
191
- */
192
- function validateParameterValue(key, value, paramDef) {
193
- if (!paramDef.validate) {
194
- return null;
195
- }
196
- switch (paramDef.validate) {
197
- case 'email': {
198
- // Basic email validation
199
- const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
200
- if (!emailRegex.test(value)) {
201
- return {
202
- parameter: key,
203
- message: `Invalid email format: ${value}`,
204
- code: 'INVALID_FORMAT',
205
- };
206
- }
207
- break;
208
- }
209
- case 'url': {
210
- try {
211
- new URL(value);
212
- }
213
- catch {
214
- return {
215
- parameter: key,
216
- message: `Invalid URL format: ${value}`,
217
- code: 'INVALID_FORMAT',
218
- };
219
- }
220
- break;
221
- }
222
- case 'rate_limit': {
223
- try {
224
- (0, types_1.parseRateLimit)(value);
225
- }
226
- catch {
227
- // Also try parsing as RateLimitConfig object
228
- const parsed = types_1.RateLimitConfigSchema.safeParse(value);
229
- if (!parsed.success) {
230
- return {
231
- parameter: key,
232
- message: `Invalid rate limit format: ${value}. Expected format: "100/hour" or RateLimitConfig object`,
233
- code: 'INVALID_FORMAT',
234
- };
235
- }
236
- }
237
- break;
238
- }
239
- }
240
- return null;
241
- }
242
- /**
243
- * Customize a profile with parameters to produce a PolicyDocument
244
- *
245
- * This applies parameter values and profile defaults to create a ready-to-use policy.
246
- *
247
- * @param profile - Profile definition or ID
248
- * @param params - Parameters to apply
249
- * @returns Customization result with policy and applied defaults
250
- * @throws ProfileError if validation fails
251
- *
252
- * @example
253
- * ```typescript
254
- * const result = customizeProfile('news-media', {
255
- * contact: 'licensing@example.com',
256
- * rate_limit: '100/hour',
257
- * });
258
- *
259
- * // result.policy is a PolicyDocument ready for use
260
- * const decision = evaluate(result.policy, context);
261
- * ```
262
- */
263
- function customizeProfile(profile, params = {}) {
264
- const def = typeof profile === 'string' ? loadProfile(profile) : profile;
265
- // Validate parameters
266
- const validation = validateProfileParams(def, params);
267
- if (!validation.valid) {
268
- const errorMessages = validation.errors.map((e) => `${e.parameter}: ${e.message}`).join(', ');
269
- throw new ProfileError(`Parameter validation failed: ${errorMessages}`, 'VALIDATION_FAILED');
270
- }
271
- // Apply defaults for missing optional parameters
272
- const appliedParams = {};
273
- for (const [key, paramDef] of Object.entries(def.parameters || {})) {
274
- if (key in params && params[key] !== undefined && params[key] !== null) {
275
- appliedParams[key] = params[key];
276
- }
277
- else if (paramDef.default !== undefined) {
278
- appliedParams[key] = paramDef.default;
279
- }
280
- }
281
- // Deep clone the policy to avoid mutations
282
- const policy = JSON.parse(JSON.stringify(def.policy));
283
- // Apply profile defaults
284
- const appliedDefaults = {};
285
- if (def.defaults?.requirements) {
286
- appliedDefaults.requirements = { ...def.defaults.requirements };
287
- }
288
- if (def.defaults?.rate_limit) {
289
- appliedDefaults.rate_limit = { ...def.defaults.rate_limit };
290
- }
291
- // If rate_limit parameter was provided, parse and apply it
292
- if (appliedParams.rate_limit) {
293
- const rateLimitValue = appliedParams.rate_limit;
294
- if (typeof rateLimitValue === 'string') {
295
- try {
296
- appliedDefaults.rate_limit = (0, types_1.parseRateLimit)(rateLimitValue);
297
- }
298
- catch {
299
- // Already validated, should not happen
300
- }
301
- }
302
- }
303
- return {
304
- policy,
305
- appliedDefaults,
306
- parameters: appliedParams,
307
- };
308
- }
309
- /**
310
- * Get all profiles as an array
311
- *
312
- * @returns Array of all profile definitions
313
- *
314
- * @example
315
- * ```typescript
316
- * const profiles = getAllProfiles();
317
- * for (const profile of profiles) {
318
- * console.log(`${profile.id}: ${profile.name}`);
319
- * }
320
- * ```
321
- */
322
- function getAllProfiles() {
323
- return profiles_1.PROFILE_IDS.map((id) => profiles_1.PROFILES[id]);
324
- }
325
- /**
326
- * Get profile summary for display purposes
327
- *
328
- * @param profile - Profile definition or ID
329
- * @returns Summary object with key information
330
- *
331
- * @example
332
- * ```typescript
333
- * const summary = getProfileSummary('news-media');
334
- * console.log(summary);
335
- * // {
336
- * // id: 'news-media',
337
- * // name: 'News Media Publisher',
338
- * // defaultDecision: 'deny',
339
- * // ruleCount: 3,
340
- * // requiresReceipt: true,
341
- * // requiredParams: ['contact']
342
- * // }
343
- * ```
344
- */
345
- function getProfileSummary(profile) {
346
- const def = typeof profile === 'string' ? loadProfile(profile) : profile;
347
- const requiredParams = [];
348
- const optionalParams = [];
349
- for (const [key, paramDef] of Object.entries(def.parameters || {})) {
350
- if (paramDef.required) {
351
- requiredParams.push(key);
352
- }
353
- else {
354
- optionalParams.push(key);
355
- }
356
- }
357
- return {
358
- id: def.id,
359
- name: def.name,
360
- description: def.description,
361
- defaultDecision: def.policy.defaults.decision,
362
- ruleCount: def.policy.rules?.length || 0,
363
- requiresReceipt: def.defaults?.requirements?.receipt ?? false,
364
- requiredParams: requiredParams.sort(),
365
- optionalParams: optionalParams.sort(),
366
- };
367
- }
368
- //# sourceMappingURL=profiles.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"profiles.js","sourceRoot":"","sources":["../src/profiles.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;;;AAwEH,oCAEC;AAeD,gCAEC;AAeD,kCAMC;AAgBD,gCAKC;AAoBD,sDA4DC;AAmFD,4CAsDC;AAeD,wCAEC;AAsBD,8CAiCC;AApaD,mDAA6E;AAE7E,mCAAgE;AAEhE;;GAEG;AACH,MAAa,YAAa,SAAQ,KAAK;IAGnB;IAFlB,YACE,OAAe,EACC,IAIO;QAEvB,KAAK,CAAC,OAAO,CAAC,CAAC;QANC,SAAI,GAAJ,IAAI,CAIG;QAGvB,IAAI,CAAC,IAAI,GAAG,cAAc,CAAC;IAC7B,CAAC;CACF;AAZD,oCAYC;AAwCD;;;;;;;;;;GAUG;AACH,SAAgB,YAAY;IAC1B,OAAO,CAAC,GAAG,sBAAW,CAAC,CAAC;AAC1B,CAAC;AAED;;;;;;;;;;;;GAYG;AACH,SAAgB,UAAU,CAAC,EAAU;IACnC,OAAO,sBAAW,CAAC,QAAQ,CAAC,EAAe,CAAC,CAAC;AAC/C,CAAC;AAED;;;;;;;;;;;;GAYG;AACH,SAAgB,WAAW,CAAC,EAAa;IACvC,MAAM,OAAO,GAAG,mBAAQ,CAAC,EAAE,CAAC,CAAC;IAC7B,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,MAAM,IAAI,YAAY,CAAC,sBAAsB,EAAE,EAAE,EAAE,mBAAmB,CAAC,CAAC;IAC1E,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC;AAED;;;;;;;;;;;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