@zucker-framework/reference 1.0.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,201 @@
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 Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ 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
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,22 @@
1
+ Zucker Framework
2
+ Copyright 2026 Lind and Zucker Framework contributors
3
+
4
+ Licensed under the Apache License, Version 2.0. See LICENSE.
5
+
6
+ The framework includes TypeScript adaptations and enhancements of concepts and
7
+ implementations from hsweb-framework and jetlinks-community, both distributed
8
+ under the Apache License, Version 2.0. Individual packages use different subsets
9
+ of the framework. The TypeScript adaptations and Node.js integrations were
10
+ modified for Zucker Framework; they are not the original upstream distribution.
11
+
12
+ hsweb-framework
13
+ https://github.com/hs-web/hsweb-framework
14
+ Copyright 2020 http://hsweb.me
15
+
16
+ jetlinks-community
17
+ https://github.com/jetlinks/jetlinks-community
18
+
19
+ See THIRD_PARTY_NOTICES for license texts and attribution for bundled dependencies
20
+ and reference implementations relevant to this package. External dependencies
21
+ remain subject to their own licenses. This NOTICE is informational and does not
22
+ modify any license or grant rights to upstream trademarks.
@@ -0,0 +1,4 @@
1
+ @zucker-framework/reference
2
+
3
+ No separately recorded third-party implementation is bundled in this package.
4
+ External dependencies retain their own licenses; see NOTICE for framework attribution.
@@ -0,0 +1,166 @@
1
+ import * as _nestjs_common from '@nestjs/common';
2
+ import { HttpException, CanActivate, ExecutionContext } from '@nestjs/common';
3
+ import { Reflector } from '@nestjs/core';
4
+
5
+ interface DataReference {
6
+ dataType: string;
7
+ dataId: string;
8
+ referenceType: string;
9
+ referenceId: string;
10
+ referenceName?: string;
11
+ }
12
+ /**
13
+ * Data reference provider SPI.
14
+ * Mirrors Java DataReferenceProvider which extends Strategy.
15
+ * Each provider handles one data type (identified by `type` / `getId()`).
16
+ */
17
+ interface DataReferenceProvider {
18
+ /** The data type this provider handles (equivalent to Java Strategy.getId()). */
19
+ type: string;
20
+ /** Get references for a specific data item. Mirrors Java getReference(dataId). */
21
+ getReferences(dataType: string, dataId: string): Promise<DataReference[]>;
22
+ /** Get all references for this data type. Mirrors Java getReferences(). */
23
+ getAllReferences?(): Promise<DataReference[]>;
24
+ }
25
+ /**
26
+ * Typed exception thrown when data cannot be deleted due to active references.
27
+ * Mirrors Java DataReferencedException (HTTP 400 / error.data.referenced).
28
+ */
29
+ declare class DataReferencedException extends HttpException {
30
+ readonly dataType: string;
31
+ readonly dataId: string;
32
+ readonly referenceList: DataReference[];
33
+ constructor(dataType: string, dataId: string, referenceList: DataReference[]);
34
+ }
35
+ /** Well-known data type constants. Mirrors Java DataReferenceManager constants. */
36
+ declare const DATA_REFERENCE_TYPES: {
37
+ readonly DEVICE_GATEWAY: "device-gateway";
38
+ readonly NETWORK: "network";
39
+ readonly RELATION: "relation";
40
+ readonly PROTOCOL: "protocol";
41
+ };
42
+ /**
43
+ * Data reference manager — collects references from all registered providers.
44
+ * Mirrors Java DefaultDataReferenceManager which extends StaticStrategyManager.
45
+ */
46
+ declare class DataReferenceManager {
47
+ private readonly logger;
48
+ private providers;
49
+ registerProvider(provider: DataReferenceProvider): void;
50
+ unregisterProvider(type: string): void;
51
+ /** Get a registered provider by type. */
52
+ getProvider(type: string): DataReferenceProvider | undefined;
53
+ /** Get all registered providers. */
54
+ getProviders(): DataReferenceProvider[];
55
+ /**
56
+ * Get references for a specific data item across all providers.
57
+ * Mirrors Java DefaultDataReferenceManager.getReferences(dataType, dataId).
58
+ */
59
+ getReferences(dataType: string, dataId: string): Promise<DataReference[]>;
60
+ /**
61
+ * Get all references for a data type (no specific dataId filter).
62
+ * Mirrors Java DefaultDataReferenceManager.getReferences(dataType).
63
+ */
64
+ getAllReferences(dataType: string): Promise<DataReference[]>;
65
+ /**
66
+ * Check if a data item is referenced. Short-circuits on first found reference.
67
+ * Mirrors Java DefaultDataReferenceManager.isReferenced() which uses hasElements().
68
+ */
69
+ hasReferences(dataType: string, dataId: string): Promise<boolean>;
70
+ /**
71
+ * Assert data is not referenced; throws DataReferencedException if it is.
72
+ * Mirrors Java DataReferenceManager.assertNotReferenced().
73
+ */
74
+ assertNoReferences(dataType: string, dataId: string): Promise<void>;
75
+ }
76
+
77
+ declare const PREVENT_DELETE_IF_REFERENCED = "zucker:reference:preventDeleteIfReferenced";
78
+ /**
79
+ * 装饰器:如果存在引用关系则阻止删除
80
+ * 用于 Controller 的 delete 方法上,配合 ReferenceGuard 使用
81
+ */
82
+ declare const PreventDeleteIfReferenced: (dataType: string) => _nestjs_common.CustomDecorator<string>;
83
+
84
+ /**
85
+ * Guard that prevents deletion when data is referenced.
86
+ * Uses DataReferencedException (HTTP 400) instead of ForbiddenException,
87
+ * matching Java DataReferenceManager.assertNotReferenced() semantics.
88
+ */
89
+ declare class ReferenceGuard implements CanActivate {
90
+ private readonly reflector;
91
+ private readonly referenceManager;
92
+ constructor(reflector: Reflector, referenceManager: DataReferenceManager);
93
+ canActivate(context: ExecutionContext): Promise<boolean>;
94
+ }
95
+
96
+ type CascadeAction = 'restrict' | 'cascade' | 'set-null' | 'no-action';
97
+ interface CascadeDeleteConfig {
98
+ /** 数据类型 */
99
+ dataType: string;
100
+ /** 删除策略 */
101
+ action: CascadeAction;
102
+ }
103
+ declare const CASCADE_DELETE_KEY = "zucker:reference:cascadeDelete";
104
+ /**
105
+ * 级联删除策略配置装饰器
106
+ */
107
+ declare const CascadeDeleteStrategy: (config: CascadeDeleteConfig) => _nestjs_common.CustomDecorator<string>;
108
+
109
+ interface OrphanChecker {
110
+ /** 数据类型 */
111
+ type: string;
112
+ /** 检查指定 ID 是否存在 */
113
+ exists(id: string): Promise<boolean>;
114
+ /** 删除指定 ID 的记录 */
115
+ delete(id: string): Promise<void>;
116
+ }
117
+ /**
118
+ * 孤儿记录清理服务
119
+ */
120
+ declare class OrphanCleanupService {
121
+ private readonly logger;
122
+ private checkers;
123
+ registerChecker(checker: OrphanChecker): void;
124
+ unregisterChecker(type: string): void;
125
+ /**
126
+ * 检查引用的目标是否存在,返回孤儿引用列表
127
+ */
128
+ findOrphans(referenceType: string, references: Array<{
129
+ id: string;
130
+ targetType: string;
131
+ targetId: string;
132
+ }>): Promise<Array<{
133
+ id: string;
134
+ targetType: string;
135
+ targetId: string;
136
+ }>>;
137
+ /**
138
+ * 清理孤儿引用
139
+ */
140
+ cleanup(referenceType: string, references: Array<{
141
+ id: string;
142
+ targetType: string;
143
+ targetId: string;
144
+ }>, onCleanup?: (ref: {
145
+ id: string;
146
+ targetType: string;
147
+ targetId: string;
148
+ }) => Promise<void>): Promise<number>;
149
+ }
150
+
151
+ declare const REFERENCE_ADDED_EVENT = "zucker.reference.added";
152
+ declare const REFERENCE_REMOVED_EVENT = "zucker.reference.removed";
153
+ interface ReferenceChangeEvent {
154
+ dataType: string;
155
+ dataId: string;
156
+ referenceType: string;
157
+ referenceId: string;
158
+ referenceName?: string;
159
+ action: 'added' | 'removed';
160
+ timestamp: Date;
161
+ }
162
+
163
+ declare class ZuckerReferenceModule {
164
+ }
165
+
166
+ export { CASCADE_DELETE_KEY, type CascadeAction, type CascadeDeleteConfig, CascadeDeleteStrategy, DATA_REFERENCE_TYPES, type DataReference, DataReferenceManager, type DataReferenceProvider, DataReferencedException, type OrphanChecker, OrphanCleanupService, PREVENT_DELETE_IF_REFERENCED, PreventDeleteIfReferenced, REFERENCE_ADDED_EVENT, REFERENCE_REMOVED_EVENT, type ReferenceChangeEvent, ReferenceGuard, ZuckerReferenceModule };
@@ -0,0 +1,166 @@
1
+ import * as _nestjs_common from '@nestjs/common';
2
+ import { HttpException, CanActivate, ExecutionContext } from '@nestjs/common';
3
+ import { Reflector } from '@nestjs/core';
4
+
5
+ interface DataReference {
6
+ dataType: string;
7
+ dataId: string;
8
+ referenceType: string;
9
+ referenceId: string;
10
+ referenceName?: string;
11
+ }
12
+ /**
13
+ * Data reference provider SPI.
14
+ * Mirrors Java DataReferenceProvider which extends Strategy.
15
+ * Each provider handles one data type (identified by `type` / `getId()`).
16
+ */
17
+ interface DataReferenceProvider {
18
+ /** The data type this provider handles (equivalent to Java Strategy.getId()). */
19
+ type: string;
20
+ /** Get references for a specific data item. Mirrors Java getReference(dataId). */
21
+ getReferences(dataType: string, dataId: string): Promise<DataReference[]>;
22
+ /** Get all references for this data type. Mirrors Java getReferences(). */
23
+ getAllReferences?(): Promise<DataReference[]>;
24
+ }
25
+ /**
26
+ * Typed exception thrown when data cannot be deleted due to active references.
27
+ * Mirrors Java DataReferencedException (HTTP 400 / error.data.referenced).
28
+ */
29
+ declare class DataReferencedException extends HttpException {
30
+ readonly dataType: string;
31
+ readonly dataId: string;
32
+ readonly referenceList: DataReference[];
33
+ constructor(dataType: string, dataId: string, referenceList: DataReference[]);
34
+ }
35
+ /** Well-known data type constants. Mirrors Java DataReferenceManager constants. */
36
+ declare const DATA_REFERENCE_TYPES: {
37
+ readonly DEVICE_GATEWAY: "device-gateway";
38
+ readonly NETWORK: "network";
39
+ readonly RELATION: "relation";
40
+ readonly PROTOCOL: "protocol";
41
+ };
42
+ /**
43
+ * Data reference manager — collects references from all registered providers.
44
+ * Mirrors Java DefaultDataReferenceManager which extends StaticStrategyManager.
45
+ */
46
+ declare class DataReferenceManager {
47
+ private readonly logger;
48
+ private providers;
49
+ registerProvider(provider: DataReferenceProvider): void;
50
+ unregisterProvider(type: string): void;
51
+ /** Get a registered provider by type. */
52
+ getProvider(type: string): DataReferenceProvider | undefined;
53
+ /** Get all registered providers. */
54
+ getProviders(): DataReferenceProvider[];
55
+ /**
56
+ * Get references for a specific data item across all providers.
57
+ * Mirrors Java DefaultDataReferenceManager.getReferences(dataType, dataId).
58
+ */
59
+ getReferences(dataType: string, dataId: string): Promise<DataReference[]>;
60
+ /**
61
+ * Get all references for a data type (no specific dataId filter).
62
+ * Mirrors Java DefaultDataReferenceManager.getReferences(dataType).
63
+ */
64
+ getAllReferences(dataType: string): Promise<DataReference[]>;
65
+ /**
66
+ * Check if a data item is referenced. Short-circuits on first found reference.
67
+ * Mirrors Java DefaultDataReferenceManager.isReferenced() which uses hasElements().
68
+ */
69
+ hasReferences(dataType: string, dataId: string): Promise<boolean>;
70
+ /**
71
+ * Assert data is not referenced; throws DataReferencedException if it is.
72
+ * Mirrors Java DataReferenceManager.assertNotReferenced().
73
+ */
74
+ assertNoReferences(dataType: string, dataId: string): Promise<void>;
75
+ }
76
+
77
+ declare const PREVENT_DELETE_IF_REFERENCED = "zucker:reference:preventDeleteIfReferenced";
78
+ /**
79
+ * 装饰器:如果存在引用关系则阻止删除
80
+ * 用于 Controller 的 delete 方法上,配合 ReferenceGuard 使用
81
+ */
82
+ declare const PreventDeleteIfReferenced: (dataType: string) => _nestjs_common.CustomDecorator<string>;
83
+
84
+ /**
85
+ * Guard that prevents deletion when data is referenced.
86
+ * Uses DataReferencedException (HTTP 400) instead of ForbiddenException,
87
+ * matching Java DataReferenceManager.assertNotReferenced() semantics.
88
+ */
89
+ declare class ReferenceGuard implements CanActivate {
90
+ private readonly reflector;
91
+ private readonly referenceManager;
92
+ constructor(reflector: Reflector, referenceManager: DataReferenceManager);
93
+ canActivate(context: ExecutionContext): Promise<boolean>;
94
+ }
95
+
96
+ type CascadeAction = 'restrict' | 'cascade' | 'set-null' | 'no-action';
97
+ interface CascadeDeleteConfig {
98
+ /** 数据类型 */
99
+ dataType: string;
100
+ /** 删除策略 */
101
+ action: CascadeAction;
102
+ }
103
+ declare const CASCADE_DELETE_KEY = "zucker:reference:cascadeDelete";
104
+ /**
105
+ * 级联删除策略配置装饰器
106
+ */
107
+ declare const CascadeDeleteStrategy: (config: CascadeDeleteConfig) => _nestjs_common.CustomDecorator<string>;
108
+
109
+ interface OrphanChecker {
110
+ /** 数据类型 */
111
+ type: string;
112
+ /** 检查指定 ID 是否存在 */
113
+ exists(id: string): Promise<boolean>;
114
+ /** 删除指定 ID 的记录 */
115
+ delete(id: string): Promise<void>;
116
+ }
117
+ /**
118
+ * 孤儿记录清理服务
119
+ */
120
+ declare class OrphanCleanupService {
121
+ private readonly logger;
122
+ private checkers;
123
+ registerChecker(checker: OrphanChecker): void;
124
+ unregisterChecker(type: string): void;
125
+ /**
126
+ * 检查引用的目标是否存在,返回孤儿引用列表
127
+ */
128
+ findOrphans(referenceType: string, references: Array<{
129
+ id: string;
130
+ targetType: string;
131
+ targetId: string;
132
+ }>): Promise<Array<{
133
+ id: string;
134
+ targetType: string;
135
+ targetId: string;
136
+ }>>;
137
+ /**
138
+ * 清理孤儿引用
139
+ */
140
+ cleanup(referenceType: string, references: Array<{
141
+ id: string;
142
+ targetType: string;
143
+ targetId: string;
144
+ }>, onCleanup?: (ref: {
145
+ id: string;
146
+ targetType: string;
147
+ targetId: string;
148
+ }) => Promise<void>): Promise<number>;
149
+ }
150
+
151
+ declare const REFERENCE_ADDED_EVENT = "zucker.reference.added";
152
+ declare const REFERENCE_REMOVED_EVENT = "zucker.reference.removed";
153
+ interface ReferenceChangeEvent {
154
+ dataType: string;
155
+ dataId: string;
156
+ referenceType: string;
157
+ referenceId: string;
158
+ referenceName?: string;
159
+ action: 'added' | 'removed';
160
+ timestamp: Date;
161
+ }
162
+
163
+ declare class ZuckerReferenceModule {
164
+ }
165
+
166
+ export { CASCADE_DELETE_KEY, type CascadeAction, type CascadeDeleteConfig, CascadeDeleteStrategy, DATA_REFERENCE_TYPES, type DataReference, DataReferenceManager, type DataReferenceProvider, DataReferencedException, type OrphanChecker, OrphanCleanupService, PREVENT_DELETE_IF_REFERENCED, PreventDeleteIfReferenced, REFERENCE_ADDED_EVENT, REFERENCE_REMOVED_EVENT, type ReferenceChangeEvent, ReferenceGuard, ZuckerReferenceModule };
package/dist/index.js ADDED
@@ -0,0 +1,333 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+
21
+ // src/index.ts
22
+ var index_exports = {};
23
+ __export(index_exports, {
24
+ CASCADE_DELETE_KEY: () => CASCADE_DELETE_KEY,
25
+ CascadeDeleteStrategy: () => CascadeDeleteStrategy,
26
+ DATA_REFERENCE_TYPES: () => DATA_REFERENCE_TYPES,
27
+ DataReferenceManager: () => DataReferenceManager,
28
+ DataReferencedException: () => DataReferencedException,
29
+ OrphanCleanupService: () => OrphanCleanupService,
30
+ PREVENT_DELETE_IF_REFERENCED: () => PREVENT_DELETE_IF_REFERENCED,
31
+ PreventDeleteIfReferenced: () => PreventDeleteIfReferenced,
32
+ REFERENCE_ADDED_EVENT: () => REFERENCE_ADDED_EVENT,
33
+ REFERENCE_REMOVED_EVENT: () => REFERENCE_REMOVED_EVENT,
34
+ ReferenceGuard: () => ReferenceGuard,
35
+ ZuckerReferenceModule: () => ZuckerReferenceModule
36
+ });
37
+ module.exports = __toCommonJS(index_exports);
38
+
39
+ // src/reference-manager.ts
40
+ var import_common = require("@nestjs/common");
41
+ function _ts_decorate(decorators, target, key, desc) {
42
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
43
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
44
+ r = Reflect.decorate(decorators, target, key, desc);
45
+ } else {
46
+ for (var i = decorators.length - 1; i >= 0; i--) {
47
+ if (d = decorators[i]) {
48
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
49
+ }
50
+ }
51
+ }
52
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
53
+ }
54
+ __name(_ts_decorate, "_ts_decorate");
55
+ var DataReferencedException = class extends import_common.HttpException {
56
+ static {
57
+ __name(this, "DataReferencedException");
58
+ }
59
+ dataType;
60
+ dataId;
61
+ referenceList;
62
+ constructor(dataType, dataId, referenceList) {
63
+ const refDescriptions = referenceList.map((r) => r.referenceName ?? `${r.referenceType}:${r.referenceId}`).join(", ");
64
+ super({
65
+ statusCode: import_common.HttpStatus.BAD_REQUEST,
66
+ message: `Data ${dataType}:${dataId} is referenced by: ${refDescriptions}`,
67
+ error: "error.data.referenced",
68
+ dataType,
69
+ dataId,
70
+ referenceList
71
+ }, import_common.HttpStatus.BAD_REQUEST);
72
+ this.dataType = dataType;
73
+ this.dataId = dataId;
74
+ this.referenceList = referenceList;
75
+ }
76
+ };
77
+ var DATA_REFERENCE_TYPES = {
78
+ DEVICE_GATEWAY: "device-gateway",
79
+ NETWORK: "network",
80
+ RELATION: "relation",
81
+ PROTOCOL: "protocol"
82
+ };
83
+ var DataReferenceManager = class _DataReferenceManager {
84
+ static {
85
+ __name(this, "DataReferenceManager");
86
+ }
87
+ logger = new import_common.Logger(_DataReferenceManager.name);
88
+ providers = [];
89
+ registerProvider(provider) {
90
+ this.providers.push(provider);
91
+ this.logger.log(`Reference provider registered: ${provider.type}`);
92
+ }
93
+ unregisterProvider(type) {
94
+ this.providers = this.providers.filter((p) => p.type !== type);
95
+ }
96
+ /** Get a registered provider by type. */
97
+ getProvider(type) {
98
+ return this.providers.find((p) => p.type === type);
99
+ }
100
+ /** Get all registered providers. */
101
+ getProviders() {
102
+ return [
103
+ ...this.providers
104
+ ];
105
+ }
106
+ /**
107
+ * Get references for a specific data item across all providers.
108
+ * Mirrors Java DefaultDataReferenceManager.getReferences(dataType, dataId).
109
+ */
110
+ async getReferences(dataType, dataId) {
111
+ if (!dataType || !dataId) return [];
112
+ const results = [];
113
+ for (const provider of this.providers) {
114
+ const refs = await provider.getReferences(dataType, dataId);
115
+ results.push(...refs);
116
+ }
117
+ return results;
118
+ }
119
+ /**
120
+ * Get all references for a data type (no specific dataId filter).
121
+ * Mirrors Java DefaultDataReferenceManager.getReferences(dataType).
122
+ */
123
+ async getAllReferences(dataType) {
124
+ const provider = this.providers.find((p) => p.type === dataType);
125
+ if (!provider || !provider.getAllReferences) {
126
+ return [];
127
+ }
128
+ return provider.getAllReferences();
129
+ }
130
+ /**
131
+ * Check if a data item is referenced. Short-circuits on first found reference.
132
+ * Mirrors Java DefaultDataReferenceManager.isReferenced() which uses hasElements().
133
+ */
134
+ async hasReferences(dataType, dataId) {
135
+ for (const provider of this.providers) {
136
+ const refs = await provider.getReferences(dataType, dataId);
137
+ if (refs.length > 0) return true;
138
+ }
139
+ return false;
140
+ }
141
+ /**
142
+ * Assert data is not referenced; throws DataReferencedException if it is.
143
+ * Mirrors Java DataReferenceManager.assertNotReferenced().
144
+ */
145
+ async assertNoReferences(dataType, dataId) {
146
+ const refs = await this.getReferences(dataType, dataId);
147
+ if (refs.length > 0) {
148
+ throw new DataReferencedException(dataType, dataId, refs);
149
+ }
150
+ }
151
+ };
152
+ DataReferenceManager = _ts_decorate([
153
+ (0, import_common.Injectable)()
154
+ ], DataReferenceManager);
155
+
156
+ // src/decorators.ts
157
+ var import_common2 = require("@nestjs/common");
158
+ var PREVENT_DELETE_IF_REFERENCED = "zucker:reference:preventDeleteIfReferenced";
159
+ var PreventDeleteIfReferenced = /* @__PURE__ */ __name((dataType) => (0, import_common2.SetMetadata)(PREVENT_DELETE_IF_REFERENCED, dataType), "PreventDeleteIfReferenced");
160
+
161
+ // src/reference.guard.ts
162
+ var import_common3 = require("@nestjs/common");
163
+ var import_core = require("@nestjs/core");
164
+ function _ts_decorate2(decorators, target, key, desc) {
165
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
166
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
167
+ r = Reflect.decorate(decorators, target, key, desc);
168
+ } else {
169
+ for (var i = decorators.length - 1; i >= 0; i--) {
170
+ if (d = decorators[i]) {
171
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
172
+ }
173
+ }
174
+ }
175
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
176
+ }
177
+ __name(_ts_decorate2, "_ts_decorate");
178
+ function _ts_metadata(metadataKey, metadataValue) {
179
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
180
+ return Reflect.metadata(metadataKey, metadataValue);
181
+ }
182
+ }
183
+ __name(_ts_metadata, "_ts_metadata");
184
+ var ReferenceGuard = class {
185
+ static {
186
+ __name(this, "ReferenceGuard");
187
+ }
188
+ reflector;
189
+ referenceManager;
190
+ constructor(reflector, referenceManager) {
191
+ this.reflector = reflector;
192
+ this.referenceManager = referenceManager;
193
+ }
194
+ async canActivate(context) {
195
+ const dataType = this.reflector.get(PREVENT_DELETE_IF_REFERENCED, context.getHandler());
196
+ if (!dataType) return true;
197
+ const request = context.switchToHttp().getRequest();
198
+ const id = request.params?.id;
199
+ if (!id) return true;
200
+ await this.referenceManager.assertNoReferences(dataType, id);
201
+ return true;
202
+ }
203
+ };
204
+ ReferenceGuard = _ts_decorate2([
205
+ (0, import_common3.Injectable)(),
206
+ _ts_metadata("design:type", Function),
207
+ _ts_metadata("design:paramtypes", [
208
+ typeof import_core.Reflector === "undefined" ? Object : import_core.Reflector,
209
+ typeof DataReferenceManager === "undefined" ? Object : DataReferenceManager
210
+ ])
211
+ ], ReferenceGuard);
212
+
213
+ // src/cascade-delete.ts
214
+ var import_common4 = require("@nestjs/common");
215
+ var CASCADE_DELETE_KEY = "zucker:reference:cascadeDelete";
216
+ var CascadeDeleteStrategy = /* @__PURE__ */ __name((config) => (0, import_common4.SetMetadata)(CASCADE_DELETE_KEY, config), "CascadeDeleteStrategy");
217
+
218
+ // src/orphan-cleanup.service.ts
219
+ var import_common5 = require("@nestjs/common");
220
+ function _ts_decorate3(decorators, target, key, desc) {
221
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
222
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
223
+ r = Reflect.decorate(decorators, target, key, desc);
224
+ } else {
225
+ for (var i = decorators.length - 1; i >= 0; i--) {
226
+ if (d = decorators[i]) {
227
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
228
+ }
229
+ }
230
+ }
231
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
232
+ }
233
+ __name(_ts_decorate3, "_ts_decorate");
234
+ var OrphanCleanupService = class _OrphanCleanupService {
235
+ static {
236
+ __name(this, "OrphanCleanupService");
237
+ }
238
+ logger = new import_common5.Logger(_OrphanCleanupService.name);
239
+ checkers = /* @__PURE__ */ new Map();
240
+ registerChecker(checker) {
241
+ this.checkers.set(checker.type, checker);
242
+ }
243
+ unregisterChecker(type) {
244
+ this.checkers.delete(type);
245
+ }
246
+ /**
247
+ * 检查引用的目标是否存在,返回孤儿引用列表
248
+ */
249
+ async findOrphans(referenceType, references) {
250
+ const orphans = [];
251
+ for (const ref of references) {
252
+ const checker = this.checkers.get(ref.targetType);
253
+ if (!checker) continue;
254
+ const exists = await checker.exists(ref.targetId);
255
+ if (!exists) {
256
+ orphans.push(ref);
257
+ }
258
+ }
259
+ return orphans;
260
+ }
261
+ /**
262
+ * 清理孤儿引用
263
+ */
264
+ async cleanup(referenceType, references, onCleanup) {
265
+ const orphans = await this.findOrphans(referenceType, references);
266
+ for (const orphan of orphans) {
267
+ if (onCleanup) {
268
+ await onCleanup(orphan);
269
+ }
270
+ this.logger.log(`Orphan reference cleaned: ${referenceType}/${orphan.id} -> ${orphan.targetType}/${orphan.targetId}`);
271
+ }
272
+ return orphans.length;
273
+ }
274
+ };
275
+ OrphanCleanupService = _ts_decorate3([
276
+ (0, import_common5.Injectable)()
277
+ ], OrphanCleanupService);
278
+
279
+ // src/reference-events.ts
280
+ var REFERENCE_ADDED_EVENT = "zucker.reference.added";
281
+ var REFERENCE_REMOVED_EVENT = "zucker.reference.removed";
282
+
283
+ // src/reference.module.ts
284
+ var import_common6 = require("@nestjs/common");
285
+ function _ts_decorate4(decorators, target, key, desc) {
286
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
287
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
288
+ r = Reflect.decorate(decorators, target, key, desc);
289
+ } else {
290
+ for (var i = decorators.length - 1; i >= 0; i--) {
291
+ if (d = decorators[i]) {
292
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
293
+ }
294
+ }
295
+ }
296
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
297
+ }
298
+ __name(_ts_decorate4, "_ts_decorate");
299
+ var ZuckerReferenceModule = class {
300
+ static {
301
+ __name(this, "ZuckerReferenceModule");
302
+ }
303
+ };
304
+ ZuckerReferenceModule = _ts_decorate4([
305
+ (0, import_common6.Global)(),
306
+ (0, import_common6.Module)({
307
+ providers: [
308
+ DataReferenceManager,
309
+ ReferenceGuard,
310
+ OrphanCleanupService
311
+ ],
312
+ exports: [
313
+ DataReferenceManager,
314
+ ReferenceGuard,
315
+ OrphanCleanupService
316
+ ]
317
+ })
318
+ ], ZuckerReferenceModule);
319
+ // Annotate the CommonJS export names for ESM import in node:
320
+ 0 && (module.exports = {
321
+ CASCADE_DELETE_KEY,
322
+ CascadeDeleteStrategy,
323
+ DATA_REFERENCE_TYPES,
324
+ DataReferenceManager,
325
+ DataReferencedException,
326
+ OrphanCleanupService,
327
+ PREVENT_DELETE_IF_REFERENCED,
328
+ PreventDeleteIfReferenced,
329
+ REFERENCE_ADDED_EVENT,
330
+ REFERENCE_REMOVED_EVENT,
331
+ ReferenceGuard,
332
+ ZuckerReferenceModule
333
+ });
package/dist/index.mjs ADDED
@@ -0,0 +1,297 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+
4
+ // src/reference-manager.ts
5
+ import { Injectable, Logger, HttpException, HttpStatus } from "@nestjs/common";
6
+ function _ts_decorate(decorators, target, key, desc) {
7
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
8
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
9
+ r = Reflect.decorate(decorators, target, key, desc);
10
+ } else {
11
+ for (var i = decorators.length - 1; i >= 0; i--) {
12
+ if (d = decorators[i]) {
13
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
14
+ }
15
+ }
16
+ }
17
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
18
+ }
19
+ __name(_ts_decorate, "_ts_decorate");
20
+ var DataReferencedException = class extends HttpException {
21
+ static {
22
+ __name(this, "DataReferencedException");
23
+ }
24
+ dataType;
25
+ dataId;
26
+ referenceList;
27
+ constructor(dataType, dataId, referenceList) {
28
+ const refDescriptions = referenceList.map((r) => r.referenceName ?? `${r.referenceType}:${r.referenceId}`).join(", ");
29
+ super({
30
+ statusCode: HttpStatus.BAD_REQUEST,
31
+ message: `Data ${dataType}:${dataId} is referenced by: ${refDescriptions}`,
32
+ error: "error.data.referenced",
33
+ dataType,
34
+ dataId,
35
+ referenceList
36
+ }, HttpStatus.BAD_REQUEST);
37
+ this.dataType = dataType;
38
+ this.dataId = dataId;
39
+ this.referenceList = referenceList;
40
+ }
41
+ };
42
+ var DATA_REFERENCE_TYPES = {
43
+ DEVICE_GATEWAY: "device-gateway",
44
+ NETWORK: "network",
45
+ RELATION: "relation",
46
+ PROTOCOL: "protocol"
47
+ };
48
+ var DataReferenceManager = class _DataReferenceManager {
49
+ static {
50
+ __name(this, "DataReferenceManager");
51
+ }
52
+ logger = new Logger(_DataReferenceManager.name);
53
+ providers = [];
54
+ registerProvider(provider) {
55
+ this.providers.push(provider);
56
+ this.logger.log(`Reference provider registered: ${provider.type}`);
57
+ }
58
+ unregisterProvider(type) {
59
+ this.providers = this.providers.filter((p) => p.type !== type);
60
+ }
61
+ /** Get a registered provider by type. */
62
+ getProvider(type) {
63
+ return this.providers.find((p) => p.type === type);
64
+ }
65
+ /** Get all registered providers. */
66
+ getProviders() {
67
+ return [
68
+ ...this.providers
69
+ ];
70
+ }
71
+ /**
72
+ * Get references for a specific data item across all providers.
73
+ * Mirrors Java DefaultDataReferenceManager.getReferences(dataType, dataId).
74
+ */
75
+ async getReferences(dataType, dataId) {
76
+ if (!dataType || !dataId) return [];
77
+ const results = [];
78
+ for (const provider of this.providers) {
79
+ const refs = await provider.getReferences(dataType, dataId);
80
+ results.push(...refs);
81
+ }
82
+ return results;
83
+ }
84
+ /**
85
+ * Get all references for a data type (no specific dataId filter).
86
+ * Mirrors Java DefaultDataReferenceManager.getReferences(dataType).
87
+ */
88
+ async getAllReferences(dataType) {
89
+ const provider = this.providers.find((p) => p.type === dataType);
90
+ if (!provider || !provider.getAllReferences) {
91
+ return [];
92
+ }
93
+ return provider.getAllReferences();
94
+ }
95
+ /**
96
+ * Check if a data item is referenced. Short-circuits on first found reference.
97
+ * Mirrors Java DefaultDataReferenceManager.isReferenced() which uses hasElements().
98
+ */
99
+ async hasReferences(dataType, dataId) {
100
+ for (const provider of this.providers) {
101
+ const refs = await provider.getReferences(dataType, dataId);
102
+ if (refs.length > 0) return true;
103
+ }
104
+ return false;
105
+ }
106
+ /**
107
+ * Assert data is not referenced; throws DataReferencedException if it is.
108
+ * Mirrors Java DataReferenceManager.assertNotReferenced().
109
+ */
110
+ async assertNoReferences(dataType, dataId) {
111
+ const refs = await this.getReferences(dataType, dataId);
112
+ if (refs.length > 0) {
113
+ throw new DataReferencedException(dataType, dataId, refs);
114
+ }
115
+ }
116
+ };
117
+ DataReferenceManager = _ts_decorate([
118
+ Injectable()
119
+ ], DataReferenceManager);
120
+
121
+ // src/decorators.ts
122
+ import { SetMetadata } from "@nestjs/common";
123
+ var PREVENT_DELETE_IF_REFERENCED = "zucker:reference:preventDeleteIfReferenced";
124
+ var PreventDeleteIfReferenced = /* @__PURE__ */ __name((dataType) => SetMetadata(PREVENT_DELETE_IF_REFERENCED, dataType), "PreventDeleteIfReferenced");
125
+
126
+ // src/reference.guard.ts
127
+ import { Injectable as Injectable2 } from "@nestjs/common";
128
+ import { Reflector } from "@nestjs/core";
129
+ function _ts_decorate2(decorators, target, key, desc) {
130
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
131
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
132
+ r = Reflect.decorate(decorators, target, key, desc);
133
+ } else {
134
+ for (var i = decorators.length - 1; i >= 0; i--) {
135
+ if (d = decorators[i]) {
136
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
137
+ }
138
+ }
139
+ }
140
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
141
+ }
142
+ __name(_ts_decorate2, "_ts_decorate");
143
+ function _ts_metadata(metadataKey, metadataValue) {
144
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
145
+ return Reflect.metadata(metadataKey, metadataValue);
146
+ }
147
+ }
148
+ __name(_ts_metadata, "_ts_metadata");
149
+ var ReferenceGuard = class {
150
+ static {
151
+ __name(this, "ReferenceGuard");
152
+ }
153
+ reflector;
154
+ referenceManager;
155
+ constructor(reflector, referenceManager) {
156
+ this.reflector = reflector;
157
+ this.referenceManager = referenceManager;
158
+ }
159
+ async canActivate(context) {
160
+ const dataType = this.reflector.get(PREVENT_DELETE_IF_REFERENCED, context.getHandler());
161
+ if (!dataType) return true;
162
+ const request = context.switchToHttp().getRequest();
163
+ const id = request.params?.id;
164
+ if (!id) return true;
165
+ await this.referenceManager.assertNoReferences(dataType, id);
166
+ return true;
167
+ }
168
+ };
169
+ ReferenceGuard = _ts_decorate2([
170
+ Injectable2(),
171
+ _ts_metadata("design:type", Function),
172
+ _ts_metadata("design:paramtypes", [
173
+ typeof Reflector === "undefined" ? Object : Reflector,
174
+ typeof DataReferenceManager === "undefined" ? Object : DataReferenceManager
175
+ ])
176
+ ], ReferenceGuard);
177
+
178
+ // src/cascade-delete.ts
179
+ import { SetMetadata as SetMetadata2 } from "@nestjs/common";
180
+ var CASCADE_DELETE_KEY = "zucker:reference:cascadeDelete";
181
+ var CascadeDeleteStrategy = /* @__PURE__ */ __name((config) => SetMetadata2(CASCADE_DELETE_KEY, config), "CascadeDeleteStrategy");
182
+
183
+ // src/orphan-cleanup.service.ts
184
+ import { Injectable as Injectable3, Logger as Logger2 } from "@nestjs/common";
185
+ function _ts_decorate3(decorators, target, key, desc) {
186
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
187
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
188
+ r = Reflect.decorate(decorators, target, key, desc);
189
+ } else {
190
+ for (var i = decorators.length - 1; i >= 0; i--) {
191
+ if (d = decorators[i]) {
192
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
193
+ }
194
+ }
195
+ }
196
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
197
+ }
198
+ __name(_ts_decorate3, "_ts_decorate");
199
+ var OrphanCleanupService = class _OrphanCleanupService {
200
+ static {
201
+ __name(this, "OrphanCleanupService");
202
+ }
203
+ logger = new Logger2(_OrphanCleanupService.name);
204
+ checkers = /* @__PURE__ */ new Map();
205
+ registerChecker(checker) {
206
+ this.checkers.set(checker.type, checker);
207
+ }
208
+ unregisterChecker(type) {
209
+ this.checkers.delete(type);
210
+ }
211
+ /**
212
+ * 检查引用的目标是否存在,返回孤儿引用列表
213
+ */
214
+ async findOrphans(referenceType, references) {
215
+ const orphans = [];
216
+ for (const ref of references) {
217
+ const checker = this.checkers.get(ref.targetType);
218
+ if (!checker) continue;
219
+ const exists = await checker.exists(ref.targetId);
220
+ if (!exists) {
221
+ orphans.push(ref);
222
+ }
223
+ }
224
+ return orphans;
225
+ }
226
+ /**
227
+ * 清理孤儿引用
228
+ */
229
+ async cleanup(referenceType, references, onCleanup) {
230
+ const orphans = await this.findOrphans(referenceType, references);
231
+ for (const orphan of orphans) {
232
+ if (onCleanup) {
233
+ await onCleanup(orphan);
234
+ }
235
+ this.logger.log(`Orphan reference cleaned: ${referenceType}/${orphan.id} -> ${orphan.targetType}/${orphan.targetId}`);
236
+ }
237
+ return orphans.length;
238
+ }
239
+ };
240
+ OrphanCleanupService = _ts_decorate3([
241
+ Injectable3()
242
+ ], OrphanCleanupService);
243
+
244
+ // src/reference-events.ts
245
+ var REFERENCE_ADDED_EVENT = "zucker.reference.added";
246
+ var REFERENCE_REMOVED_EVENT = "zucker.reference.removed";
247
+
248
+ // src/reference.module.ts
249
+ import { Module, Global } from "@nestjs/common";
250
+ function _ts_decorate4(decorators, target, key, desc) {
251
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
252
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
253
+ r = Reflect.decorate(decorators, target, key, desc);
254
+ } else {
255
+ for (var i = decorators.length - 1; i >= 0; i--) {
256
+ if (d = decorators[i]) {
257
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
258
+ }
259
+ }
260
+ }
261
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
262
+ }
263
+ __name(_ts_decorate4, "_ts_decorate");
264
+ var ZuckerReferenceModule = class {
265
+ static {
266
+ __name(this, "ZuckerReferenceModule");
267
+ }
268
+ };
269
+ ZuckerReferenceModule = _ts_decorate4([
270
+ Global(),
271
+ Module({
272
+ providers: [
273
+ DataReferenceManager,
274
+ ReferenceGuard,
275
+ OrphanCleanupService
276
+ ],
277
+ exports: [
278
+ DataReferenceManager,
279
+ ReferenceGuard,
280
+ OrphanCleanupService
281
+ ]
282
+ })
283
+ ], ZuckerReferenceModule);
284
+ export {
285
+ CASCADE_DELETE_KEY,
286
+ CascadeDeleteStrategy,
287
+ DATA_REFERENCE_TYPES,
288
+ DataReferenceManager,
289
+ DataReferencedException,
290
+ OrphanCleanupService,
291
+ PREVENT_DELETE_IF_REFERENCED,
292
+ PreventDeleteIfReferenced,
293
+ REFERENCE_ADDED_EVENT,
294
+ REFERENCE_REMOVED_EVENT,
295
+ ReferenceGuard,
296
+ ZuckerReferenceModule
297
+ };
package/package.json ADDED
@@ -0,0 +1,36 @@
1
+ {
2
+ "name": "@zucker-framework/reference",
3
+ "version": "1.0.0",
4
+ "main": "dist/index.js",
5
+ "module": "dist/index.mjs",
6
+ "types": "dist/index.d.ts",
7
+ "files": [
8
+ "dist",
9
+ "LICENSE",
10
+ "NOTICE",
11
+ "THIRD_PARTY_NOTICES"
12
+ ],
13
+ "dependencies": {
14
+ "@zucker-framework/core": "1.0.0"
15
+ },
16
+ "peerDependencies": {
17
+ "@nestjs/common": "^12.0.0",
18
+ "@nestjs/core": "^12.0.0"
19
+ },
20
+ "license": "Apache-2.0",
21
+ "author": "Lind",
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "git+https://github.com/Lind-pro/zucker-framework.git",
25
+ "directory": "packages/reference"
26
+ },
27
+ "publishConfig": {
28
+ "access": "public",
29
+ "registry": "https://registry.npmjs.org/"
30
+ },
31
+ "scripts": {
32
+ "build": "tsup src/index.ts --format cjs,esm --dts",
33
+ "clean": "rm -rf dist",
34
+ "lint": "eslint src/"
35
+ }
36
+ }