@living-architecture/riviere-role-enforcement 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to the Licensor for inclusion in the Work by the copyright
52
+ owner or by an individual or Legal Entity authorized to submit on behalf
53
+ of the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2026 Nick Tune
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/dist/bin.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ export {};
3
+ //# sourceMappingURL=bin.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bin.d.ts","sourceRoot":"","sources":["../src/bin.ts"],"names":[],"mappings":""}
package/dist/bin.js ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import { main } from './cli';
3
+ process.exitCode = main(process.argv.slice(2));
@@ -0,0 +1,20 @@
1
+ import type { RoleEnforcementConfig } from '../config/role-enforcement-config';
2
+ interface OxlintRuleOptions {
3
+ configDir: string;
4
+ configDisplayPath: string;
5
+ layers: RoleEnforcementConfig['layers'];
6
+ roles: RoleEnforcementConfig['roles'];
7
+ }
8
+ interface OxlintConfig {
9
+ ignorePatterns: string[];
10
+ jsPlugins: Array<{
11
+ name: string;
12
+ specifier: string;
13
+ }>;
14
+ rules: {
15
+ 'riviere-role-enforcement/enforce-roles': ['error', OxlintRuleOptions];
16
+ };
17
+ }
18
+ export declare function createOxlintConfig(config: RoleEnforcementConfig, configDir: string, configPath: string, pluginPath: string): OxlintConfig;
19
+ export {};
20
+ //# sourceMappingURL=create-oxlint-config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"create-oxlint-config.d.ts","sourceRoot":"","sources":["../../src/cli/create-oxlint-config.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,mCAAmC,CAAA;AAE9E,UAAU,iBAAiB;IACzB,SAAS,EAAE,MAAM,CAAA;IACjB,iBAAiB,EAAE,MAAM,CAAA;IACzB,MAAM,EAAE,qBAAqB,CAAC,QAAQ,CAAC,CAAA;IACvC,KAAK,EAAE,qBAAqB,CAAC,OAAO,CAAC,CAAA;CACtC;AAED,UAAU,YAAY;IACpB,cAAc,EAAE,MAAM,EAAE,CAAA;IACxB,SAAS,EAAE,KAAK,CAAC;QACf,IAAI,EAAE,MAAM,CAAA;QACZ,SAAS,EAAE,MAAM,CAAA;KAClB,CAAC,CAAA;IACF,KAAK,EAAE;QAAE,wCAAwC,EAAE,CAAC,OAAO,EAAE,iBAAiB,CAAC,CAAA;KAAE,CAAA;CAClF;AAED,wBAAgB,kBAAkB,CAChC,MAAM,EAAE,qBAAqB,EAC7B,SAAS,EAAE,MAAM,EACjB,UAAU,EAAE,MAAM,EAClB,UAAU,EAAE,MAAM,GACjB,YAAY,CAqBd"}
@@ -0,0 +1,28 @@
1
+ import path from 'node:path';
2
+ export function createOxlintConfig(config, configDir, configPath, pluginPath) {
3
+ return {
4
+ ignorePatterns: config.ignorePatterns,
5
+ jsPlugins: [
6
+ {
7
+ name: 'riviere-role-enforcement',
8
+ specifier: toImportSpecifier(configDir, pluginPath),
9
+ },
10
+ ],
11
+ rules: {
12
+ 'riviere-role-enforcement/enforce-roles': [
13
+ 'error',
14
+ {
15
+ configDir,
16
+ configDisplayPath: path.relative(configDir, configPath),
17
+ layers: config.layers,
18
+ roles: config.roles,
19
+ },
20
+ ],
21
+ },
22
+ };
23
+ }
24
+ function toImportSpecifier(configDir, pluginPath) {
25
+ const relativePath = path.relative(configDir, pluginPath);
26
+ const normalizedPath = relativePath.replaceAll('\\', '/');
27
+ return normalizedPath.startsWith('.') ? normalizedPath : `./${normalizedPath}`;
28
+ }
@@ -0,0 +1,39 @@
1
+ import type { PathLike } from 'node:fs';
2
+ export interface RoleEnforcementRunResult {
3
+ durationMs: number;
4
+ exitCode: number;
5
+ stderr: string;
6
+ stdout: string;
7
+ }
8
+ export declare class RoleEnforcementExecutionError extends Error {
9
+ constructor(message: string);
10
+ }
11
+ interface RoleEnforcementRuntimeDeps {
12
+ now: () => number;
13
+ readdirSync: (rootDir: PathLike, options: {
14
+ recursive: true;
15
+ withFileTypes: true;
16
+ }) => Array<{
17
+ isFile: () => boolean;
18
+ name: string;
19
+ parentPath: string;
20
+ }>;
21
+ realpathSync: (filePath: PathLike) => string;
22
+ rmSync: (filePath: string, options: {
23
+ force: true;
24
+ }) => void;
25
+ spawnSync: (command: string, args: string[], options: {
26
+ cwd: string;
27
+ encoding: 'utf8';
28
+ }) => {
29
+ error?: Error;
30
+ status: number | null;
31
+ stderr: string;
32
+ stdout: string;
33
+ };
34
+ writeFileSync: (filePath: string, contents: string) => void;
35
+ }
36
+ export declare function runRoleEnforcement(configPath: string, runtimeDeps?: RoleEnforcementRuntimeDeps): RoleEnforcementRunResult;
37
+ export declare function formatRoleEnforcementFailure(error: unknown): string;
38
+ export {};
39
+ //# sourceMappingURL=run-role-enforcement.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-role-enforcement.d.ts","sourceRoot":"","sources":["../../src/cli/run-role-enforcement.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAA;AAUvC,MAAM,WAAW,wBAAwB;IACvC,UAAU,EAAE,MAAM,CAAA;IAClB,QAAQ,EAAE,MAAM,CAAA;IAChB,MAAM,EAAE,MAAM,CAAA;IACd,MAAM,EAAE,MAAM,CAAA;CACf;AAED,qBAAa,6BAA8B,SAAQ,KAAK;gBAC1C,OAAO,EAAE,MAAM;CAI5B;AAED,UAAU,0BAA0B;IAClC,GAAG,EAAE,MAAM,MAAM,CAAA;IACjB,WAAW,EAAE,CACX,OAAO,EAAE,QAAQ,EACjB,OAAO,EAAE;QACP,SAAS,EAAE,IAAI,CAAA;QACf,aAAa,EAAE,IAAI,CAAA;KACpB,KACE,KAAK,CAAC;QACT,MAAM,EAAE,MAAM,OAAO,CAAA;QACrB,IAAI,EAAE,MAAM,CAAA;QACZ,UAAU,EAAE,MAAM,CAAA;KACnB,CAAC,CAAA;IACF,YAAY,EAAE,CAAC,QAAQ,EAAE,QAAQ,KAAK,MAAM,CAAA;IAC5C,MAAM,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE;QAAE,KAAK,EAAE,IAAI,CAAA;KAAE,KAAK,IAAI,CAAA;IAC5D,SAAS,EAAE,CACT,OAAO,EAAE,MAAM,EACf,IAAI,EAAE,MAAM,EAAE,EACd,OAAO,EAAE;QACP,GAAG,EAAE,MAAM,CAAA;QACX,QAAQ,EAAE,MAAM,CAAA;KACjB,KACE;QACH,KAAK,CAAC,EAAE,KAAK,CAAA;QACb,MAAM,EAAE,MAAM,GAAG,IAAI,CAAA;QACrB,MAAM,EAAE,MAAM,CAAA;QACd,MAAM,EAAE,MAAM,CAAA;KACf,CAAA;IACD,aAAa,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,KAAK,IAAI,CAAA;CAC5D;AAWD,wBAAgB,kBAAkB,CAChC,UAAU,EAAE,MAAM,EAClB,WAAW,GAAE,0BAA+C,GAC3D,wBAAwB,CAyD1B;AAkCD,wBAAgB,4BAA4B,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CASnE"}
@@ -0,0 +1,77 @@
1
+ import { readdirSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { spawnSync } from 'node:child_process';
4
+ import { performance } from 'node:perf_hooks';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { minimatch } from 'minimatch';
7
+ import { loadRoleEnforcementConfig } from '../config/load-role-enforcement-config';
8
+ import { RoleEnforcementConfigError } from '../config/role-enforcement-config-error';
9
+ import { createOxlintConfig } from './create-oxlint-config';
10
+ export class RoleEnforcementExecutionError extends Error {
11
+ constructor(message) {
12
+ super(message);
13
+ this.name = 'RoleEnforcementExecutionError';
14
+ }
15
+ }
16
+ const defaultRuntimeDeps = {
17
+ now: () => performance.now(),
18
+ readdirSync: (rootDir, options) => readdirSync(rootDir, options),
19
+ realpathSync,
20
+ rmSync,
21
+ spawnSync,
22
+ writeFileSync,
23
+ };
24
+ export function runRoleEnforcement(configPath, runtimeDeps = defaultRuntimeDeps) {
25
+ const loadedConfig = loadRoleEnforcementConfig(configPath);
26
+ const currentDir = path.dirname(fileURLToPath(import.meta.url));
27
+ const canonicalConfigDir = runtimeDeps.realpathSync(loadedConfig.configDir);
28
+ const pluginPath = path.resolve(currentDir, '..', '..', 'role-enforcement-plugin.mjs');
29
+ const oxlintBinaryPath = path.resolve(currentDir, '..', '..', '..', '..', 'node_modules', '.bin', 'oxlint');
30
+ const oxlintConfigPath = path.join(loadedConfig.configDir, `.oxlintrc.role-enforcement.${process.pid}.${Date.now()}.json`);
31
+ const oxlintConfig = createOxlintConfig(loadedConfig.config, canonicalConfigDir, loadedConfig.configPath, pluginPath);
32
+ const lintTargets = resolveLintTargets(canonicalConfigDir, loadedConfig.config.include, loadedConfig.config.ignorePatterns, runtimeDeps.readdirSync);
33
+ runtimeDeps.writeFileSync(oxlintConfigPath, JSON.stringify(oxlintConfig, null, 2));
34
+ const start = runtimeDeps.now();
35
+ const commandResult = runtimeDeps.spawnSync(oxlintBinaryPath, ['-c', oxlintConfigPath, ...lintTargets], {
36
+ cwd: loadedConfig.configDir,
37
+ encoding: 'utf8',
38
+ });
39
+ const durationMs = runtimeDeps.now() - start;
40
+ runtimeDeps.rmSync(oxlintConfigPath, { force: true });
41
+ if (commandResult.error !== undefined) {
42
+ throw new RoleEnforcementExecutionError(commandResult.error.message);
43
+ }
44
+ return {
45
+ durationMs,
46
+ exitCode: commandResult.status ?? 1,
47
+ stderr: commandResult.stderr,
48
+ stdout: commandResult.stdout,
49
+ };
50
+ }
51
+ function resolveLintTargets(configDir, includePatterns, ignorePatterns, readDirectory) {
52
+ return walkFiles(configDir, readDirectory)
53
+ .filter((filePath) => matchesAny(filePath, includePatterns))
54
+ .filter((filePath) => !matchesAny(filePath, ignorePatterns));
55
+ }
56
+ function walkFiles(rootDir, readDirectory) {
57
+ const entries = readDirectory(rootDir, {
58
+ recursive: true,
59
+ withFileTypes: true,
60
+ });
61
+ return entries
62
+ .filter((entry) => entry.isFile())
63
+ .map((entry) => normalizePath(path.relative(rootDir, path.join(entry.parentPath, entry.name))));
64
+ }
65
+ function matchesAny(filePath, patterns) {
66
+ return patterns.some((pattern) => minimatch(filePath, pattern, { dot: true }));
67
+ }
68
+ function normalizePath(value) {
69
+ return value.replaceAll('\\', '/');
70
+ }
71
+ export function formatRoleEnforcementFailure(error) {
72
+ if (error instanceof RoleEnforcementConfigError ||
73
+ error instanceof RoleEnforcementExecutionError) {
74
+ return error.message;
75
+ }
76
+ return error instanceof Error ? error.message : 'Unknown role enforcement failure.';
77
+ }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export declare function main(args: string[]): number;
2
+ //# sourceMappingURL=cli.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":"AAIA,wBAAgB,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,MAAM,CAqB3C"}
package/dist/cli.js ADDED
@@ -0,0 +1,23 @@
1
+ import { formatRoleEnforcementFailure, runRoleEnforcement } from './cli/run-role-enforcement';
2
+ export function main(args) {
3
+ const [configPath] = args;
4
+ if (configPath === undefined) {
5
+ process.stderr.write('Usage: riviere-role-enforcement <config-path>\n');
6
+ return 1;
7
+ }
8
+ try {
9
+ const result = runRoleEnforcement(configPath);
10
+ if (result.stdout !== '') {
11
+ process.stdout.write(result.stdout);
12
+ }
13
+ if (result.stderr !== '') {
14
+ process.stderr.write(result.stderr);
15
+ }
16
+ process.stderr.write(`Role enforcement completed in ${Math.round(result.durationMs)}ms\n`);
17
+ return result.exitCode;
18
+ }
19
+ catch (error) {
20
+ process.stderr.write(`${formatRoleEnforcementFailure(error)}\n`);
21
+ return 1;
22
+ }
23
+ }
@@ -0,0 +1,8 @@
1
+ import type * as roleConfig from './role-enforcement-config';
2
+ export interface LoadedRoleEnforcementConfig {
3
+ config: roleConfig.RoleEnforcementConfig;
4
+ configDir: string;
5
+ configPath: string;
6
+ }
7
+ export declare function loadRoleEnforcementConfig(configPath: string): LoadedRoleEnforcementConfig;
8
+ //# sourceMappingURL=load-role-enforcement-config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"load-role-enforcement-config.d.ts","sourceRoot":"","sources":["../../src/config/load-role-enforcement-config.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,KAAK,UAAU,MAAM,2BAA2B,CAAA;AAc5D,MAAM,WAAW,2BAA2B;IAC1C,MAAM,EAAE,UAAU,CAAC,qBAAqB,CAAA;IACxC,SAAS,EAAE,MAAM,CAAA;IACjB,UAAU,EAAE,MAAM,CAAA;CACnB;AAED,wBAAgB,yBAAyB,CAAC,UAAU,EAAE,MAAM,GAAG,2BAA2B,CAUzF"}
@@ -0,0 +1,109 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import Ajv2020 from 'ajv/dist/2020';
5
+ import addFormats from 'ajv-formats';
6
+ import { RoleEnforcementConfigError } from './role-enforcement-config-error';
7
+ const ajv = new Ajv2020({
8
+ allErrors: true,
9
+ strict: false,
10
+ });
11
+ addFormats(ajv);
12
+ const currentDir = path.dirname(fileURLToPath(import.meta.url));
13
+ const schemaPath = path.resolve(currentDir, '..', '..', 'role-enforcement.schema.json');
14
+ const schema = readSchema(schemaPath);
15
+ const validateSchema = ajv.compile(schema);
16
+ export function loadRoleEnforcementConfig(configPath) {
17
+ const absolutePath = path.resolve(configPath);
18
+ const rawConfig = readConfigJson(absolutePath);
19
+ const validatedConfig = validateRoleEnforcementConfig(rawConfig);
20
+ return {
21
+ config: validatedConfig,
22
+ configDir: path.dirname(absolutePath),
23
+ configPath: absolutePath,
24
+ };
25
+ }
26
+ function readConfigJson(configPath) {
27
+ try {
28
+ return JSON.parse(readFileSync(configPath, 'utf8'));
29
+ }
30
+ catch (error) {
31
+ throw new RoleEnforcementConfigError(`Invalid role enforcement config: ${readConfigReadFailure(error)}`);
32
+ }
33
+ }
34
+ function readSchema(schemaFilePath) {
35
+ const parsedSchema = JSON.parse(readFileSync(schemaFilePath, 'utf8'));
36
+ /* v8 ignore next -- @preserve: bundled schema file is guaranteed to be an object */
37
+ if (!isObjectRecord(parsedSchema)) {
38
+ throw new RoleEnforcementConfigError('Invalid role enforcement config schema.');
39
+ }
40
+ return parsedSchema;
41
+ }
42
+ function validateRoleEnforcementConfig(config) {
43
+ const valid = validateSchema(config);
44
+ if (!valid) {
45
+ throw new RoleEnforcementConfigError(
46
+ /* v8 ignore next -- @preserve: Ajv always provides concrete error entries for invalid configs in this package */
47
+ `Invalid role enforcement config: ${formatSchemaErrors(validateSchema.errors ?? []).join('; ')}`);
48
+ }
49
+ const roleNames = new Set(config.roles.map((role) => role.name));
50
+ const errorMessages = [
51
+ ...config.roles.flatMap((role, index) => validateRoleDefinition(role, index, roleNames)),
52
+ ...validateLayerReferences(config.layers, roleNames),
53
+ ];
54
+ if (errorMessages.length > 0) {
55
+ throw new RoleEnforcementConfigError(`Invalid role enforcement config: ${errorMessages.join('; ')}`);
56
+ }
57
+ return config;
58
+ }
59
+ function validateRoleDefinition(role, index, definedRoleNames) {
60
+ const errorMessages = [];
61
+ if (role.allowedNames !== undefined && role.nameMatches !== undefined) {
62
+ errorMessages.push(`roles.${index}.nameMatches: Role definition cannot declare both 'allowedNames' and 'nameMatches'.`);
63
+ }
64
+ if (role.nameMatches !== undefined) {
65
+ try {
66
+ new RegExp(role.nameMatches, 'u');
67
+ }
68
+ catch {
69
+ errorMessages.push(`roles.${index}.nameMatches: '${role.nameMatches}' is not a valid regular expression.`);
70
+ }
71
+ }
72
+ if (role.forbiddenDependencies !== undefined) {
73
+ for (const depName of role.forbiddenDependencies) {
74
+ if (!definedRoleNames.has(depName)) {
75
+ errorMessages.push(`roles.${index}.forbiddenDependencies: '${depName}' is not a defined role.`);
76
+ }
77
+ }
78
+ }
79
+ return errorMessages;
80
+ }
81
+ function validateLayerReferences(layers, definedRoleNames) {
82
+ const errorMessages = [];
83
+ for (const [layerName, layer] of Object.entries(layers)) {
84
+ for (const roleName of layer.allowedRoles) {
85
+ if (!definedRoleNames.has(roleName)) {
86
+ errorMessages.push(`layers.${layerName}.allowedRoles: '${roleName}' is not a defined role.`);
87
+ }
88
+ }
89
+ }
90
+ return errorMessages;
91
+ }
92
+ function formatSchemaErrors(errors) {
93
+ return errors.map((error) =>
94
+ /* v8 ignore next -- @preserve: Ajv always populates message for generated validation errors here */
95
+ `${formatInstancePath(error.instancePath)}: ${error.message ?? 'Schema validation failed.'}`);
96
+ }
97
+ function formatInstancePath(instancePath) {
98
+ if (instancePath === '') {
99
+ return '$';
100
+ }
101
+ return instancePath.slice(1).split('/').join('.');
102
+ }
103
+ function readConfigReadFailure(error) {
104
+ /* v8 ignore next -- @preserve: JSON/file parsing in Node always throws Error instances here */
105
+ return error instanceof Error ? error.message : 'Unknown config read failure.';
106
+ }
107
+ function isObjectRecord(value) {
108
+ return typeof value === 'object' && value !== null;
109
+ }
@@ -0,0 +1,4 @@
1
+ export declare class RoleEnforcementConfigError extends Error {
2
+ constructor(message: string);
3
+ }
4
+ //# sourceMappingURL=role-enforcement-config-error.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"role-enforcement-config-error.d.ts","sourceRoot":"","sources":["../../src/config/role-enforcement-config-error.ts"],"names":[],"mappings":"AAAA,qBAAa,0BAA2B,SAAQ,KAAK;gBACvC,OAAO,EAAE,MAAM;CAI5B"}
@@ -0,0 +1,6 @@
1
+ export class RoleEnforcementConfigError extends Error {
2
+ constructor(message) {
3
+ super(message);
4
+ this.name = 'RoleEnforcementConfigError';
5
+ }
6
+ }
@@ -0,0 +1,21 @@
1
+ export type RoleTarget = 'class' | 'function' | 'interface' | 'type-alias';
2
+ export interface LayerDefinition {
3
+ allowedRoles: string[];
4
+ paths: string[];
5
+ }
6
+ export interface RoleDefinition {
7
+ allowedInputs?: string[];
8
+ allowedNames?: string[];
9
+ allowedOutputs?: string[];
10
+ forbiddenDependencies?: string[];
11
+ name: string;
12
+ nameMatches?: string;
13
+ targets: RoleTarget[];
14
+ }
15
+ export interface RoleEnforcementConfig {
16
+ ignorePatterns: string[];
17
+ include: string[];
18
+ layers: Record<string, LayerDefinition>;
19
+ roles: RoleDefinition[];
20
+ }
21
+ //# sourceMappingURL=role-enforcement-config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"role-enforcement-config.d.ts","sourceRoot":"","sources":["../../src/config/role-enforcement-config.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,UAAU,GAAG,OAAO,GAAG,UAAU,GAAG,WAAW,GAAG,YAAY,CAAA;AAE1E,MAAM,WAAW,eAAe;IAC9B,YAAY,EAAE,MAAM,EAAE,CAAA;IACtB,KAAK,EAAE,MAAM,EAAE,CAAA;CAChB;AAED,MAAM,WAAW,cAAc;IAC7B,aAAa,CAAC,EAAE,MAAM,EAAE,CAAA;IACxB,YAAY,CAAC,EAAE,MAAM,EAAE,CAAA;IACvB,cAAc,CAAC,EAAE,MAAM,EAAE,CAAA;IACzB,qBAAqB,CAAC,EAAE,MAAM,EAAE,CAAA;IAChC,IAAI,EAAE,MAAM,CAAA;IACZ,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,OAAO,EAAE,UAAU,EAAE,CAAA;CACtB;AAED,MAAM,WAAW,qBAAqB;IACpC,cAAc,EAAE,MAAM,EAAE,CAAA;IACxB,OAAO,EAAE,MAAM,EAAE,CAAA;IACjB,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,eAAe,CAAC,CAAA;IACvC,KAAK,EAAE,cAAc,EAAE,CAAA;CACxB"}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,5 @@
1
+ export type { LayerDefinition, RoleDefinition, RoleEnforcementConfig, RoleTarget, } from './config/role-enforcement-config';
2
+ export { loadRoleEnforcementConfig, type LoadedRoleEnforcementConfig, } from './config/load-role-enforcement-config';
3
+ export { RoleEnforcementConfigError } from './config/role-enforcement-config-error';
4
+ export { formatRoleEnforcementFailure, RoleEnforcementExecutionError, runRoleEnforcement, type RoleEnforcementRunResult, } from './cli/run-role-enforcement';
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,eAAe,EACf,cAAc,EACd,qBAAqB,EACrB,UAAU,GACX,MAAM,kCAAkC,CAAA;AACzC,OAAO,EACL,yBAAyB,EACzB,KAAK,2BAA2B,GACjC,MAAM,uCAAuC,CAAA;AAC9C,OAAO,EAAE,0BAA0B,EAAE,MAAM,wCAAwC,CAAA;AACnF,OAAO,EACL,4BAA4B,EAC5B,6BAA6B,EAC7B,kBAAkB,EAClB,KAAK,wBAAwB,GAC9B,MAAM,4BAA4B,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { loadRoleEnforcementConfig, } from './config/load-role-enforcement-config';
2
+ export { RoleEnforcementConfigError } from './config/role-enforcement-config-error';
3
+ export { formatRoleEnforcementFailure, RoleEnforcementExecutionError, runRoleEnforcement, } from './cli/run-role-enforcement';
package/package.json ADDED
@@ -0,0 +1,36 @@
1
+ {
2
+ "name": "@living-architecture/riviere-role-enforcement",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "publishConfig": {
6
+ "access": "public"
7
+ },
8
+ "main": "./dist/index.js",
9
+ "module": "./dist/index.js",
10
+ "types": "./dist/index.d.ts",
11
+ "bin": {
12
+ "riviere-role-enforcement": "./dist/bin.js"
13
+ },
14
+ "exports": {
15
+ "./package.json": "./package.json",
16
+ ".": {
17
+ "@living-architecture/source": "./src/index.ts",
18
+ "types": "./dist/index.d.ts",
19
+ "import": "./dist/index.js",
20
+ "default": "./dist/index.js"
21
+ },
22
+ "./schema.json": "./role-enforcement.schema.json",
23
+ "./plugin": "./role-enforcement-plugin.mjs"
24
+ },
25
+ "files": [
26
+ "dist",
27
+ "role-enforcement-plugin.mjs",
28
+ "role-enforcement.schema.json",
29
+ "!**/*.tsbuildinfo"
30
+ ],
31
+ "dependencies": {
32
+ "ajv": "^8.17.1",
33
+ "ajv-formats": "^3.0.1",
34
+ "minimatch": "^10.0.1"
35
+ }
36
+ }
@@ -0,0 +1,454 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import { minimatch } from 'minimatch'
4
+
5
+ const ROLE_TAG = /@riviere-role\s+([a-z][a-z0-9-]*)/g
6
+
7
+ export default {
8
+ meta: { name: 'riviere-role-enforcement' },
9
+ rules: {
10
+ 'enforce-roles': {
11
+ meta: { schema: [{ type: 'object' }] },
12
+ create(context) {
13
+ const [options] = context.options
14
+ const roleMap = new Map(options.roles.map((role) => [role.name, role]))
15
+ const layerEntries = Object.entries(options.layers ?? {})
16
+ const sourceCode = context.sourceCode
17
+ const fileCache = new Map()
18
+ const importCache = new Map()
19
+ const relativeFilePath = normalizePath(
20
+ readRelativeFilePath(context.filename, options.configDir),
21
+ )
22
+ const filename = path.resolve(options.configDir, relativeFilePath)
23
+
24
+ if (
25
+ !filename.endsWith('.ts') ||
26
+ filename.endsWith('.spec.ts') ||
27
+ filename.endsWith('.test.ts')
28
+ ) {
29
+ return {}
30
+ }
31
+
32
+ const fileRoles = []
33
+
34
+ return {
35
+ FunctionDeclaration(node) {
36
+ validateDeclaration(node, 'function')
37
+ },
38
+ ClassDeclaration(node) {
39
+ validateDeclaration(node, 'class')
40
+ },
41
+ TSInterfaceDeclaration(node) {
42
+ validateDeclaration(node, 'interface')
43
+ },
44
+ TSTypeAliasDeclaration(node) {
45
+ validateDeclaration(node, 'type-alias')
46
+ },
47
+ 'Program:exit'() {
48
+ validateForbiddenDependencies()
49
+ },
50
+ }
51
+
52
+ function validateDeclaration(node, target) {
53
+ if (!isTopLevelExported(node)) {
54
+ return
55
+ }
56
+
57
+ const name = readDeclarationName(node)
58
+ if (name === null) {
59
+ return
60
+ }
61
+
62
+ const annotationNode = readAnnotationNode(node)
63
+ const roleNames = readRoleNames(sourceCode, annotationNode)
64
+ if (roleNames.length === 0) {
65
+ report(
66
+ node,
67
+ `Missing @riviere-role annotation for '${name}'. See ${options.configDisplayPath}`,
68
+ )
69
+ return
70
+ }
71
+
72
+ if (roleNames.length > 1) {
73
+ report(
74
+ node,
75
+ `Multiple @riviere-role annotations found for '${name}'. See ${options.configDisplayPath}`,
76
+ )
77
+ return
78
+ }
79
+
80
+ const [roleName] = roleNames
81
+ const role = roleMap.get(roleName)
82
+ if (role === undefined) {
83
+ report(
84
+ node,
85
+ `Unknown role '${roleName}' on '${name}'. See ${options.configDisplayPath}`,
86
+ )
87
+ return
88
+ }
89
+
90
+ if (!role.targets.includes(target)) {
91
+ report(
92
+ node,
93
+ `Role '${roleName}' does not allow target '${target}'. See ${options.configDisplayPath}`,
94
+ )
95
+ return
96
+ }
97
+
98
+ if (!isRoleAllowedInFile(roleName, relativeFilePath)) {
99
+ report(
100
+ node,
101
+ `${roleName} cannot live in ${relativeFilePath}. See ${options.configDisplayPath}`,
102
+ )
103
+ return
104
+ }
105
+
106
+ if (!matchesName(name, role)) {
107
+ report(
108
+ node,
109
+ `Role '${roleName}' does not allow name '${name}'. See ${options.configDisplayPath}`,
110
+ )
111
+ return
112
+ }
113
+
114
+ fileRoles.push(roleName)
115
+
116
+ if (target === 'function') {
117
+ validateFunctionContract(node, role, name)
118
+ }
119
+ }
120
+
121
+ function isRoleAllowedInFile(roleName, filePath) {
122
+ const fileDir = normalizePath(path.dirname(filePath))
123
+ return layerEntries.some(
124
+ ([, layer]) =>
125
+ layer.allowedRoles.includes(roleName) &&
126
+ layer.paths.some((pattern) => matchesExpandedPattern(fileDir, pattern)),
127
+ )
128
+ }
129
+
130
+ function validateForbiddenDependencies() {
131
+ const forbiddenSet = collectForbiddenRoles(fileRoles, roleMap)
132
+ if (forbiddenSet.size === 0) {
133
+ return
134
+ }
135
+
136
+ for (const statement of readRelativeImportStatements()) {
137
+ reportForbiddenImports(statement, forbiddenSet)
138
+ }
139
+ }
140
+
141
+ function readRelativeImportStatements() {
142
+ return sourceCode.ast.body.filter(
143
+ (statement) =>
144
+ statement.type === 'ImportDeclaration' &&
145
+ typeof statement.source.value === 'string' &&
146
+ statement.source.value.startsWith('.'),
147
+ )
148
+ }
149
+
150
+ function reportForbiddenImports(statement, forbiddenSet) {
151
+ const resolvedFile = resolveTypeFile(filename, statement.source.value)
152
+ if (resolvedFile === null) {
153
+ return
154
+ }
155
+
156
+ const importedRoles = readAllExportedRoles(resolvedFile)
157
+ for (const importedRole of importedRoles) {
158
+ if (forbiddenSet.has(importedRole)) {
159
+ report(
160
+ statement,
161
+ `Forbidden dependency: this file (${fileRoles.join(', ')}) cannot import from a file exporting '${importedRole}'. See ${options.configDisplayPath}`,
162
+ )
163
+ }
164
+ }
165
+ }
166
+
167
+ function readAllExportedRoles(filePath) {
168
+ const sourceText = readFileText(filePath)
169
+ if (sourceText === null) {
170
+ return []
171
+ }
172
+
173
+ const roles = []
174
+ const lines = sourceText.split('\n')
175
+ for (let i = 0; i < lines.length; i++) {
176
+ const roleMatch = ROLE_TAG.exec(lines[i])
177
+ ROLE_TAG.lastIndex = 0
178
+ if (roleMatch === null) {
179
+ continue
180
+ }
181
+
182
+ for (let j = i + 1; j < lines.length; j++) {
183
+ const trimmed = lines[j].trim()
184
+ if (trimmed === '' || trimmed.startsWith('*') || trimmed.startsWith('/**')) {
185
+ continue
186
+ }
187
+ if (/^export\s+(?:interface|type|function|class)\s+\w+/.test(trimmed)) {
188
+ roles.push(roleMatch[1])
189
+ }
190
+ break
191
+ }
192
+ }
193
+ return roles
194
+ }
195
+
196
+ function validateFunctionContract(node, role, name) {
197
+ if (Array.isArray(role.allowedInputs)) {
198
+ if (node.params.length !== 1) {
199
+ report(
200
+ node,
201
+ `Role '${role.name}' must accept exactly one parameter on '${name}'. See ${options.configDisplayPath}`,
202
+ )
203
+ return
204
+ }
205
+
206
+ const inputRole = readTypeRole(node.params[0].typeAnnotation, filename)
207
+ if (inputRole === null || !role.allowedInputs.includes(inputRole)) {
208
+ report(
209
+ node,
210
+ `Role '${role.name}' only allows inputs [${role.allowedInputs.join(', ')}] on '${name}'. See ${options.configDisplayPath}`,
211
+ )
212
+ return
213
+ }
214
+ }
215
+
216
+ if (Array.isArray(role.allowedOutputs)) {
217
+ const outputRole = readTypeRole(node.returnType, filename)
218
+ if (outputRole === null || !role.allowedOutputs.includes(outputRole)) {
219
+ report(
220
+ node,
221
+ `Role '${role.name}' only allows outputs [${role.allowedOutputs.join(', ')}] on '${name}'. See ${options.configDisplayPath}`,
222
+ )
223
+ }
224
+ }
225
+ }
226
+
227
+ function readTypeRole(typeAnnotation, currentFile) {
228
+ if (typeAnnotation === null || typeAnnotation === undefined) {
229
+ return null
230
+ }
231
+
232
+ if (typeAnnotation.type !== 'TSTypeAnnotation') {
233
+ return null
234
+ }
235
+
236
+ const innerType = typeAnnotation.typeAnnotation
237
+ if (innerType.type !== 'TSTypeReference' || innerType.typeName.type !== 'Identifier') {
238
+ return null
239
+ }
240
+
241
+ const localTypeName = innerType.typeName.name
242
+ const importedReference = readImportedReference(localTypeName, currentFile)
243
+ if (importedReference !== null) {
244
+ return readExportedRole(importedReference.filePath, importedReference.exportedName)
245
+ }
246
+
247
+ return readExportedRole(currentFile, localTypeName)
248
+ }
249
+
250
+ function readImportedReference(localTypeName, currentFile) {
251
+ const cacheKey = `${currentFile}::${localTypeName}`
252
+ if (importCache.has(cacheKey)) {
253
+ return importCache.get(cacheKey)
254
+ }
255
+
256
+ for (const statement of sourceCode.ast.body) {
257
+ const importedReference = readImportDeclarationReference(
258
+ statement,
259
+ localTypeName,
260
+ currentFile,
261
+ )
262
+ if (importedReference === undefined) {
263
+ continue
264
+ }
265
+
266
+ importCache.set(cacheKey, importedReference)
267
+ return importedReference
268
+ }
269
+
270
+ importCache.set(cacheKey, null)
271
+ return null
272
+ }
273
+
274
+ function readExportedRole(filePath, exportedName) {
275
+ const sourceText = readFileText(filePath)
276
+ if (sourceText === null) {
277
+ return null
278
+ }
279
+
280
+ const escapedName = escapeRegExp(exportedName)
281
+ const exportPattern = new RegExp(
282
+ String.raw`/\*\*[\s\S]*?@riviere-role\s+([a-z][a-z0-9-]*)[\s\S]*?\*/\s*export\s+(?:interface|type|function|class)\s+${escapedName}\b`,
283
+ 'm',
284
+ )
285
+ const match = sourceText.match(exportPattern)
286
+ return match === null ? null : (match[1] ?? null)
287
+ }
288
+
289
+ function readFileText(filePath) {
290
+ if (fileCache.has(filePath)) {
291
+ return fileCache.get(filePath)
292
+ }
293
+
294
+ if (!fs.existsSync(filePath)) {
295
+ fileCache.set(filePath, null)
296
+ return null
297
+ }
298
+
299
+ const fileText = fs.readFileSync(filePath, 'utf8')
300
+ fileCache.set(filePath, fileText)
301
+ return fileText
302
+ }
303
+
304
+ function report(node, message) {
305
+ context.report({
306
+ message,
307
+ node,
308
+ })
309
+ }
310
+ },
311
+ },
312
+ },
313
+ }
314
+
315
+ function matchesExpandedPattern(fileDir, pattern) {
316
+ return expandCommaPath(pattern).some(
317
+ (expanded) =>
318
+ minimatch(fileDir, expanded, { dot: true }) ||
319
+ minimatch(fileDir, `${expanded}/**`, { dot: true }),
320
+ )
321
+ }
322
+
323
+ function expandCommaPath(pattern) {
324
+ const segments = pattern.split('/')
325
+ const segmentAlternatives = segments.map((s) => s.split(','))
326
+ return cartesianProduct(segmentAlternatives).map((combo) => combo.join('/**/'))
327
+ }
328
+
329
+ function cartesianProduct(arrays) {
330
+ return arrays.reduce(
331
+ (acc, alternatives) => acc.flatMap((combo) => alternatives.map((alt) => [...combo, alt])),
332
+ [[]],
333
+ )
334
+ }
335
+
336
+ function collectForbiddenRoles(fileRoles, roleMap) {
337
+ const forbiddenSet = new Set()
338
+ for (const roleName of fileRoles) {
339
+ const role = roleMap.get(roleName)
340
+ if (role !== undefined && Array.isArray(role.forbiddenDependencies)) {
341
+ for (const dep of role.forbiddenDependencies) {
342
+ forbiddenSet.add(dep)
343
+ }
344
+ }
345
+ }
346
+ return forbiddenSet
347
+ }
348
+
349
+ function isTopLevelExported(node) {
350
+ const exportParent = readAnnotationNode(node)
351
+ return (
352
+ exportParent.parent?.type === 'Program' &&
353
+ (exportParent.type === 'ExportNamedDeclaration' ||
354
+ exportParent.type === 'ExportDefaultDeclaration')
355
+ )
356
+ }
357
+
358
+ function readAnnotationNode(node) {
359
+ return node.parent?.type === 'ExportNamedDeclaration' ||
360
+ node.parent?.type === 'ExportDefaultDeclaration'
361
+ ? node.parent
362
+ : node
363
+ }
364
+
365
+ function readDeclarationName(node) {
366
+ if ('id' in node && node.id != null) {
367
+ return node.id.name
368
+ }
369
+
370
+ if ('key' in node && node.key?.type === 'Identifier') {
371
+ return node.key.name
372
+ }
373
+
374
+ return 'id' in node && 'name' in node ? node.name : null
375
+ }
376
+
377
+ function readRoleNames(sourceCode, node) {
378
+ const comments = sourceCode.getCommentsBefore(node)
379
+ const roleNames = []
380
+
381
+ for (const comment of comments) {
382
+ let match = ROLE_TAG.exec(comment.value)
383
+ while (match !== null) {
384
+ roleNames.push(match[1])
385
+ match = ROLE_TAG.exec(comment.value)
386
+ }
387
+ ROLE_TAG.lastIndex = 0
388
+ }
389
+
390
+ return [...new Set(roleNames)]
391
+ }
392
+
393
+ function matchesName(name, role) {
394
+ if (Array.isArray(role.allowedNames)) {
395
+ return role.allowedNames.includes(name)
396
+ }
397
+
398
+ if (typeof role.nameMatches === 'string') {
399
+ return new RegExp(role.nameMatches, 'u').test(name)
400
+ }
401
+
402
+ return true
403
+ }
404
+
405
+ function resolveTypeFile(currentFile, importSource) {
406
+ const sourceDir = path.dirname(currentFile)
407
+ const basePath = path.resolve(sourceDir, importSource)
408
+ const candidates = [basePath, `${basePath}.ts`, path.join(basePath, 'index.ts')]
409
+
410
+ return candidates.find((candidate) => fs.existsSync(candidate)) ?? null
411
+ }
412
+
413
+ function normalizePath(value) {
414
+ return value.replaceAll('\\', '/')
415
+ }
416
+
417
+ function readRelativeFilePath(filename, configDir) {
418
+ return path.isAbsolute(filename) ? path.relative(configDir, filename) : filename
419
+ }
420
+
421
+ function escapeRegExp(value) {
422
+ return value.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`)
423
+ }
424
+
425
+ function readImportDeclarationReference(statement, localTypeName, currentFile) {
426
+ if (statement.type !== 'ImportDeclaration') {
427
+ return undefined
428
+ }
429
+
430
+ if (typeof statement.source.value !== 'string' || !statement.source.value.startsWith('.')) {
431
+ return undefined
432
+ }
433
+
434
+ const importedSpecifier = (statement.specifiers ?? []).find(
435
+ (specifier) => specifier.type === 'ImportSpecifier' && specifier.local.name === localTypeName,
436
+ )
437
+ if (importedSpecifier === undefined) {
438
+ return undefined
439
+ }
440
+
441
+ const importedName =
442
+ importedSpecifier.imported.type === 'Identifier'
443
+ ? importedSpecifier.imported.name
444
+ : importedSpecifier.imported.value
445
+ const resolvedFile = resolveTypeFile(currentFile, statement.source.value)
446
+ if (resolvedFile === null) {
447
+ return null
448
+ }
449
+
450
+ return {
451
+ exportedName: importedName,
452
+ filePath: resolvedFile,
453
+ }
454
+ }
@@ -0,0 +1,115 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://living-architecture.dev/schemas/role-enforcement.schema.json",
4
+ "type": "object",
5
+ "additionalProperties": false,
6
+ "required": ["include", "ignorePatterns", "layers", "roles"],
7
+ "properties": {
8
+ "include": {
9
+ "type": "array",
10
+ "minItems": 1,
11
+ "items": {
12
+ "type": "string",
13
+ "minLength": 1
14
+ }
15
+ },
16
+ "ignorePatterns": {
17
+ "type": "array",
18
+ "items": {
19
+ "type": "string",
20
+ "minLength": 1
21
+ }
22
+ },
23
+ "layers": {
24
+ "type": "object",
25
+ "minProperties": 1,
26
+ "additionalProperties": {
27
+ "type": "object",
28
+ "additionalProperties": false,
29
+ "required": ["paths", "allowedRoles"],
30
+ "properties": {
31
+ "paths": {
32
+ "type": "array",
33
+ "minItems": 1,
34
+ "items": {
35
+ "type": "string",
36
+ "minLength": 1
37
+ }
38
+ },
39
+ "allowedRoles": {
40
+ "type": "array",
41
+ "minItems": 1,
42
+ "items": {
43
+ "type": "string",
44
+ "minLength": 1
45
+ },
46
+ "uniqueItems": true
47
+ }
48
+ }
49
+ }
50
+ },
51
+ "roles": {
52
+ "type": "array",
53
+ "minItems": 1,
54
+ "items": {
55
+ "type": "object",
56
+ "additionalProperties": false,
57
+ "required": ["name", "targets"],
58
+ "properties": {
59
+ "name": {
60
+ "type": "string",
61
+ "pattern": "^[a-z][a-z0-9-]*$"
62
+ },
63
+ "targets": {
64
+ "type": "array",
65
+ "minItems": 1,
66
+ "items": {
67
+ "enum": ["class", "function", "interface", "type-alias"]
68
+ },
69
+ "uniqueItems": true
70
+ },
71
+ "allowedNames": {
72
+ "type": "array",
73
+ "minItems": 1,
74
+ "items": {
75
+ "type": "string",
76
+ "minLength": 1
77
+ },
78
+ "uniqueItems": true
79
+ },
80
+ "nameMatches": {
81
+ "type": "string",
82
+ "minLength": 1
83
+ },
84
+ "allowedInputs": {
85
+ "type": "array",
86
+ "minItems": 1,
87
+ "items": {
88
+ "type": "string",
89
+ "minLength": 1
90
+ },
91
+ "uniqueItems": true
92
+ },
93
+ "allowedOutputs": {
94
+ "type": "array",
95
+ "minItems": 1,
96
+ "items": {
97
+ "type": "string",
98
+ "minLength": 1
99
+ },
100
+ "uniqueItems": true
101
+ },
102
+ "forbiddenDependencies": {
103
+ "type": "array",
104
+ "minItems": 1,
105
+ "items": {
106
+ "type": "string",
107
+ "minLength": 1
108
+ },
109
+ "uniqueItems": true
110
+ }
111
+ }
112
+ }
113
+ }
114
+ }
115
+ }