@ng-openapi/zod 0.1.3-pr-127-fix-125-sanitize-generated-identifiers-9082a48.0 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/index.cjs +54 -416
  2. package/index.d.ts +1 -1
  3. package/index.js +54 -416
  4. package/package.json +1 -1
package/index.cjs CHANGED
@@ -38,238 +38,6 @@ module.exports = __toCommonJS(index_exports);
38
38
  // src/lib/zod.generator.ts
39
39
  var path2 = __toESM(require("path"), 1);
40
40
 
41
- // ../../shared/src/errors.ts
42
- var NG_OPENAPI_ERROR_BRAND = "__ngOpenApiError";
43
- var ERROR_LINEAGE = /* @__PURE__ */ new WeakMap();
44
- var FALLBACK_LINEAGE = Object.freeze([
45
- "NgOpenApiError"
46
- ]);
47
- function registerError(cls, lineage) {
48
- ERROR_LINEAGE.set(cls, Object.freeze([
49
- ...lineage
50
- ]));
51
- return cls;
52
- }
53
- __name(registerError, "registerError");
54
- function inheritedLineage(cls) {
55
- for (let current = cls; typeof current === "function"; current = Object.getPrototypeOf(current)) {
56
- const lineage = ERROR_LINEAGE.get(current);
57
- if (lineage) {
58
- return lineage;
59
- }
60
- }
61
- return FALLBACK_LINEAGE;
62
- }
63
- __name(inheritedLineage, "inheritedLineage");
64
- var NgOpenApiError = class extends Error {
65
- static {
66
- __name(this, "NgOpenApiError");
67
- }
68
- /** The underlying error that caused this one, when there is one. */
69
- cause;
70
- constructor(message, cause) {
71
- super(message);
72
- const lineage = inheritedLineage(new.target);
73
- this.name = lineage[0];
74
- this.cause = cause;
75
- Object.defineProperty(this, NG_OPENAPI_ERROR_BRAND, {
76
- value: lineage,
77
- enumerable: false,
78
- writable: false,
79
- configurable: false
80
- });
81
- }
82
- /**
83
- * `message` and `name` are non-enumerable on Error, so the default
84
- * JSON.stringify dropped both — the least useful possible serialization for
85
- * something that exists to be logged.
86
- *
87
- * The payload is spread rather than enumerated: `source`, `issues`,
88
- * `operation`, `names` and `placeholders` are why these classes are typed
89
- * in the first place, and listing fields by hand silently drops whichever
90
- * ones a later subclass adds.
91
- */
92
- toJSON() {
93
- const cause = this.cause instanceof Error ? this.cause.message : this.cause;
94
- return {
95
- name: this.name,
96
- message: this.message,
97
- ...cause === void 0 ? {} : {
98
- cause
99
- },
100
- // Own enumerable properties: the brand is deliberately not one.
101
- ...Object.fromEntries(Object.entries(this).filter(([key]) => key !== "cause"))
102
- };
103
- }
104
- /**
105
- * Recognizes branded errors from another bundled copy of this module, so
106
- * `error instanceof SpecLoadError` works for a plugin-thrown error too.
107
- * The prototype chain is checked first, so a caller's own subclass of these
108
- * classes still matches even though it carries no lineage entry.
109
- *
110
- * Never throws and never runs foreign code: both reflective reads sit
111
- * inside the try, because a Proxy traps `getPrototypeOf` just as readily as
112
- * `getOwnPropertyDescriptor`.
113
- */
114
- static [Symbol.hasInstance](value) {
115
- if (typeof value !== "object" || value === null) {
116
- return false;
117
- }
118
- try {
119
- if (Object.prototype.isPrototypeOf.call(this.prototype, value)) {
120
- return true;
121
- }
122
- const expected = ERROR_LINEAGE.get(this)?.[0];
123
- if (expected === void 0) {
124
- return false;
125
- }
126
- const descriptor = Object.getOwnPropertyDescriptor(value, NG_OPENAPI_ERROR_BRAND);
127
- if (!descriptor || descriptor.enumerable || !("value" in descriptor)) {
128
- return false;
129
- }
130
- return Array.isArray(descriptor.value) && descriptor.value.includes(expected);
131
- } catch {
132
- return false;
133
- }
134
- }
135
- };
136
- registerError(NgOpenApiError, [
137
- "NgOpenApiError"
138
- ]);
139
- var SpecLoadError = class extends NgOpenApiError {
140
- static {
141
- __name(this, "SpecLoadError");
142
- }
143
- /** The file path or URL that failed to load. */
144
- source;
145
- constructor(message, source, cause) {
146
- super(message, cause);
147
- this.source = source;
148
- }
149
- };
150
- registerError(SpecLoadError, [
151
- "SpecLoadError",
152
- "NgOpenApiError"
153
- ]);
154
- var SpecParseError = class extends NgOpenApiError {
155
- static {
156
- __name(this, "SpecParseError");
157
- }
158
- /** The file path or URL the content came from, when known. */
159
- source;
160
- constructor(message, source, cause) {
161
- super(message, cause);
162
- this.source = source;
163
- }
164
- };
165
- registerError(SpecParseError, [
166
- "SpecParseError",
167
- "NgOpenApiError"
168
- ]);
169
- function describeOperation(operation) {
170
- const location = `(${operation.method}) ${operation.path}`;
171
- return operation.operationId ? `${operation.operationId} (${location})` : location;
172
- }
173
- __name(describeOperation, "describeOperation");
174
- function captureOperation(operation) {
175
- return Object.freeze({
176
- operationId: operation.operationId,
177
- method: operation.method,
178
- path: operation.path
179
- });
180
- }
181
- __name(captureOperation, "captureOperation");
182
- var InvalidIdentifierError = class extends NgOpenApiError {
183
- static {
184
- __name(this, "InvalidIdentifierError");
185
- }
186
- /** The rejected name, verbatim; absent when no name could be derived. */
187
- identifier;
188
- /** The operation whose name was being derived. */
189
- operation;
190
- constructor(message, operation, identifier) {
191
- super(message);
192
- this.operation = captureOperation(operation);
193
- this.identifier = identifier;
194
- }
195
- };
196
- registerError(InvalidIdentifierError, [
197
- "InvalidIdentifierError",
198
- "NgOpenApiError"
199
- ]);
200
- var DuplicateGeneratedNameError = class extends NgOpenApiError {
201
- static {
202
- __name(this, "DuplicateGeneratedNameError");
203
- }
204
- /** The colliding generated names. */
205
- names;
206
- /** The operations that produced them, when known. */
207
- operations;
208
- constructor(message, names, operations = []) {
209
- super(message);
210
- this.names = Object.freeze([
211
- ...names
212
- ]);
213
- this.operations = Object.freeze(operations.map(captureOperation));
214
- }
215
- };
216
- registerError(DuplicateGeneratedNameError, [
217
- "DuplicateGeneratedNameError",
218
- "NgOpenApiError"
219
- ]);
220
- var UnresolvedPathTemplateError = class extends NgOpenApiError {
221
- static {
222
- __name(this, "UnresolvedPathTemplateError");
223
- }
224
- /** The path as written in the spec. */
225
- path;
226
- /** Placeholder names with no declared parameter. */
227
- placeholders;
228
- constructor(message, path3, placeholders) {
229
- super(message);
230
- this.path = path3;
231
- this.placeholders = Object.freeze([
232
- ...placeholders
233
- ]);
234
- }
235
- };
236
- registerError(UnresolvedPathTemplateError, [
237
- "UnresolvedPathTemplateError",
238
- "NgOpenApiError"
239
- ]);
240
- var ConfigValidationError = class extends NgOpenApiError {
241
- static {
242
- __name(this, "ConfigValidationError");
243
- }
244
- issues;
245
- constructor(issues) {
246
- super(`Invalid ng-openapi configuration:
247
- ${issues.map((issue) => ` - ${issue}`).join("\n")}`);
248
- this.issues = Object.freeze([
249
- ...issues
250
- ]);
251
- }
252
- };
253
- registerError(ConfigValidationError, [
254
- "ConfigValidationError",
255
- "NgOpenApiError"
256
- ]);
257
- var ConfigLoadError = class extends NgOpenApiError {
258
- static {
259
- __name(this, "ConfigLoadError");
260
- }
261
- /** Path of the config file that failed to load. */
262
- source;
263
- constructor(message, source, cause) {
264
- super(message, cause);
265
- this.source = source;
266
- }
267
- };
268
- registerError(ConfigLoadError, [
269
- "ConfigLoadError",
270
- "NgOpenApiError"
271
- ]);
272
-
273
41
  // ../../../node_modules/js-yaml/dist/js-yaml.mjs
274
42
  function isNothing(subject) {
275
43
  return typeof subject === "undefined" || subject === null;
@@ -2979,69 +2747,16 @@ var CONTENT_TYPES = {
2979
2747
  JSON: "application/json"
2980
2748
  };
2981
2749
 
2982
- // ../../shared/src/emit/literal.emit.ts
2983
- function quoteLiteral(value) {
2984
- return `'${escapeSingleQuoted(value)}'`;
2985
- }
2986
- __name(quoteLiteral, "quoteLiteral");
2987
- function escapeSingleQuoted(value) {
2988
- return value.replace(/[\\']/g, (char) => `\\${char}`).replace(/\r/g, "\\r").replace(/\n/g, "\\n");
2989
- }
2990
- __name(escapeSingleQuoted, "escapeSingleQuoted");
2991
- function emitObjectKey(name, quoteStyle = "double") {
2992
- const quoted = quoteStyle === "single" ? quoteLiteral(name) : `"${escapeDoubleQuoted(name)}"`;
2993
- return name === "__proto__" ? `[${quoted}]` : quoted;
2994
- }
2995
- __name(emitObjectKey, "emitObjectKey");
2996
- function escapeDoubleQuoted(value) {
2997
- return value.replace(/[\\"]/g, (char) => `\\${char}`).replace(/\r/g, "\\r").replace(/\n/g, "\\n");
2998
- }
2999
- __name(escapeDoubleQuoted, "escapeDoubleQuoted");
3000
-
3001
2750
  // ../../shared/src/utils/string.utils.ts
3002
- var IDENTIFIER_SEPARATORS = /(?:_|[^\p{ID_Continue}$])+(.)?/gu;
3003
- var INVALID_IDENTIFIER_START = /^[^\p{ID_Start}$_]/u;
3004
- function toIdentifier(converted) {
3005
- if (converted === "") {
3006
- return "_";
3007
- }
3008
- return converted.replace(INVALID_IDENTIFIER_START, (char) => `_${char}`);
3009
- }
3010
- __name(toIdentifier, "toIdentifier");
3011
2751
  function camelCase(str2) {
3012
- const converted = str2.replace(IDENTIFIER_SEPARATORS, (_, char) => char ? char.toUpperCase() : "").replace(/^./u, (char) => char.toLowerCase());
3013
- return toIdentifier(converted);
2752
+ return str2.replace(/[-_.\s]+(.)?/g, (_, char) => char ? char.toUpperCase() : "").replace(/^./, (char) => char.toLowerCase());
3014
2753
  }
3015
2754
  __name(camelCase, "camelCase");
3016
2755
  function pascalCase(str2) {
3017
- const converted = str2.replace(IDENTIFIER_SEPARATORS, (_, char) => char ? char.toUpperCase() : "").replace(/^./u, (char) => char.toUpperCase());
3018
- return toIdentifier(converted);
2756
+ return str2.replace(/[-_.\s]+(.)?/g, (_, char) => char ? char.toUpperCase() : "").replace(/^./, (char) => char.toUpperCase());
3019
2757
  }
3020
2758
  __name(pascalCase, "pascalCase");
3021
2759
 
3022
- // ../../shared/src/utils/functions/argument-names.ts
3023
- var SERVICE_ARGUMENT_PROFILE = Object.freeze({
3024
- reserved: Object.freeze([
3025
- "observe",
3026
- "options",
3027
- "url",
3028
- "params",
3029
- "headers",
3030
- "formData",
3031
- "formBody"
3032
- ]),
3033
- bindsRequestBody: true
3034
- });
3035
- var RESOURCE_ARGUMENT_PROFILE = Object.freeze({
3036
- reserved: Object.freeze([
3037
- "resourceOptions",
3038
- "requestOptions",
3039
- "params",
3040
- "headers"
3041
- ]),
3042
- bindsRequestBody: false
3043
- });
3044
-
3045
2760
  // ../../shared/src/utils/project.utils.ts
3046
2761
  function listGeneratedFileNames(project, directoryPath, suffix) {
3047
2762
  const directory = project.getDirectory(directoryPath);
@@ -3052,65 +2767,6 @@ function listGeneratedFileNames(project, directoryPath, suffix) {
3052
2767
  }
3053
2768
  __name(listGeneratedFileNames, "listGeneratedFileNames");
3054
2769
 
3055
- // ../../shared/src/utils/functions/controller-groups.ts
3056
- function groupOperationsByController(operations, onWarning) {
3057
- const groups = {};
3058
- const controllerByFold = /* @__PURE__ */ new Map();
3059
- const tagSpellings = /* @__PURE__ */ new Map();
3060
- const namelessTags = /* @__PURE__ */ new Set();
3061
- operations.forEach((operation) => {
3062
- const tag = operation.tags?.[0];
3063
- let rawName = "Default";
3064
- if (tag !== void 0) {
3065
- rawName = tag;
3066
- } else {
3067
- const pathParts = operation.path.split("/").filter((part) => part && !part.startsWith("{"));
3068
- if (pathParts.length > 1) {
3069
- rawName = pathParts[1];
3070
- }
3071
- }
3072
- const sanitized = pascalCase(rawName);
3073
- const isNameless = !/\p{L}/u.test(sanitized);
3074
- const candidate = isNameless ? "Default" : sanitized;
3075
- const fold = candidate.toLowerCase();
3076
- const controllerName = controllerByFold.get(fold) ?? candidate;
3077
- controllerByFold.set(fold, controllerName);
3078
- if (tag !== void 0 && isNameless) {
3079
- namelessTags.add(tag);
3080
- } else if (tag !== void 0) {
3081
- const spellings = tagSpellings.get(controllerName) ?? /* @__PURE__ */ new Set();
3082
- spellings.add(tag);
3083
- tagSpellings.set(controllerName, spellings);
3084
- }
3085
- if (!groups[controllerName]) {
3086
- groups[controllerName] = [];
3087
- }
3088
- groups[controllerName].push(operation);
3089
- });
3090
- for (const tag of namelessTags) {
3091
- onWarning?.(`Tag "${tag}" contains no characters usable in a name \u2014 its operations are generated into the "Default" controller. Rename the tag to give them a file of their own.`);
3092
- }
3093
- for (const [controllerName, spellings] of tagSpellings) {
3094
- if (spellings.size > 1) {
3095
- onWarning?.(`Tags ${[
3096
- ...spellings
3097
- ].map((name) => `"${name}"`).join(" and ")} all map to the controller "${controllerName}" \u2014 their operations are generated into one file. Rename one tag to keep them apart.`);
3098
- }
3099
- }
3100
- return groups;
3101
- }
3102
- __name(groupOperationsByController, "groupOperationsByController");
3103
-
3104
- // ../../shared/src/utils/functions/method-names.ts
3105
- var RESERVED_MEMBER_NAMES = Object.freeze([
3106
- "constructor",
3107
- "httpClient",
3108
- "basePath",
3109
- "clientContextToken",
3110
- "createContextWithClientId"
3111
- ]);
3112
- var RESERVED_MEMBER_SET = new Set(RESERVED_MEMBER_NAMES);
3113
-
3114
2770
  // ../../shared/src/config/constants.ts
3115
2771
  var disableLinting = `// @ts-nocheck
3116
2772
  /* eslint-disable */
@@ -3210,14 +2866,14 @@ var ZodSchemaBuilder = class {
3210
2866
  } else if (!buildOptions.required) {
3211
2867
  zodSchema = `${zodSchema}.optional()`;
3212
2868
  }
3213
- if (typeof schema2.description === "string" && schema2.description) {
3214
- zodSchema = `${zodSchema}.describe('${escapeSingleQuoted(schema2.description)}')`;
2869
+ if (schema2.description) {
2870
+ zodSchema = `${zodSchema}.describe('${this.escapeString(schema2.description)}')`;
3215
2871
  }
3216
2872
  return zodSchema;
3217
2873
  }
3218
2874
  async buildStringSchema(schema2, buildOptions) {
3219
2875
  if (schema2.enum && schema2.enum.every((v) => typeof v === "string")) {
3220
- const enumValues = schema2.enum.map((v) => emitEnumMember(v)).join(", ");
2876
+ const enumValues = schema2.enum.map((v) => `'${this.escapeString(String(v))}'`).join(", ");
3221
2877
  return `z.enum([${enumValues}])`;
3222
2878
  }
3223
2879
  if (schema2.format) {
@@ -3251,14 +2907,15 @@ var ZodSchemaBuilder = class {
3251
2907
  }
3252
2908
  }
3253
2909
  let zodString = buildOptions.coerce ? "z.coerce.string()" : "z.string()";
3254
- if (typeof schema2.minLength === "number" && Number.isFinite(schema2.minLength)) {
2910
+ if (schema2.minLength !== void 0) {
3255
2911
  zodString += `.min(${schema2.minLength})`;
3256
2912
  }
3257
- if (typeof schema2.maxLength === "number" && Number.isFinite(schema2.maxLength)) {
2913
+ if (schema2.maxLength !== void 0) {
3258
2914
  zodString += `.max(${schema2.maxLength})`;
3259
2915
  }
3260
- if (typeof schema2.pattern === "string") {
3261
- zodString += `.regex(new RegExp(${quoteLiteral(stripRegexDelimiters(schema2.pattern))}))`;
2916
+ if (schema2.pattern) {
2917
+ const escapedPattern = this.escapeRegex(schema2.pattern);
2918
+ zodString += `.regex(new RegExp('${escapedPattern}'))`;
3262
2919
  }
3263
2920
  return zodString;
3264
2921
  }
@@ -3271,13 +2928,13 @@ var ZodSchemaBuilder = class {
3271
2928
  return `z.union([${literals}])`;
3272
2929
  }
3273
2930
  let zodNumber = buildOptions.coerce ? "z.coerce.number()" : "z.number()";
3274
- if (typeof schema2.minimum === "number" && Number.isFinite(schema2.minimum)) {
2931
+ if (schema2.minimum !== void 0) {
3275
2932
  zodNumber += `.min(${schema2.minimum})`;
3276
2933
  }
3277
- if (typeof schema2.maximum === "number" && Number.isFinite(schema2.maximum)) {
2934
+ if (schema2.maximum !== void 0) {
3278
2935
  zodNumber += `.max(${schema2.maximum})`;
3279
2936
  }
3280
- if (typeof schema2.multipleOf === "number" && Number.isFinite(schema2.multipleOf)) {
2937
+ if (schema2.multipleOf !== void 0) {
3281
2938
  zodNumber += `.multipleOf(${schema2.multipleOf})`;
3282
2939
  }
3283
2940
  if (schema2.type === "integer") {
@@ -3304,10 +2961,10 @@ var ZodSchemaBuilder = class {
3304
2961
  required: true
3305
2962
  });
3306
2963
  let zodArray = `z.array(${itemSchema})`;
3307
- if (typeof schema2.minItems === "number" && Number.isFinite(schema2.minItems)) {
2964
+ if (schema2.minItems !== void 0) {
3308
2965
  zodArray += `.min(${schema2.minItems})`;
3309
2966
  }
3310
- if (typeof schema2.maxItems === "number" && Number.isFinite(schema2.maxItems)) {
2967
+ if (schema2.maxItems !== void 0) {
3311
2968
  zodArray += `.max(${schema2.maxItems})`;
3312
2969
  }
3313
2970
  return zodArray;
@@ -3351,7 +3008,7 @@ var ZodSchemaBuilder = class {
3351
3008
  ...buildOptions,
3352
3009
  required: isRequired
3353
3010
  });
3354
- properties.push(` ${emitObjectKey(propName)}: ${propZodSchema}`);
3011
+ properties.push(` "${propName}": ${propZodSchema}`);
3355
3012
  }
3356
3013
  let objectSchema = `z.object({
3357
3014
  ${properties.join(",\n")}
@@ -3385,51 +3042,37 @@ ${properties.join(",\n")}
3385
3042
  }
3386
3043
  return schema2.type || "any";
3387
3044
  }
3388
- /**
3389
- * A default value as a zod `.default(...)` literal.
3390
- *
3391
- * Recursive, because a default is arbitrary JSON: object keys are spec text
3392
- * and went into the literal raw (`{ my-key: 1 }` is a syntax error, a
3393
- * `__proto__` key is the setter), and nested values went through
3394
- * `String()`, which emits `[object Object]` into source. Not
3395
- * `emitEnumMember`: that helper serializes an unknown value as a *string*
3396
- * because a z.enum member must be one, which turned `default: ["x", null]`
3397
- * into `['x', 'null']`.
3398
- */
3399
3045
  generateDefaultValue(defaultValue) {
3400
3046
  if (typeof defaultValue === "string") {
3401
- return quoteLiteral(defaultValue);
3047
+ return `'${this.escapeString(defaultValue)}'`;
3402
3048
  }
3403
- if (typeof defaultValue === "boolean" || typeof defaultValue === "number" && Number.isFinite(defaultValue)) {
3049
+ if (typeof defaultValue === "number" || typeof defaultValue === "boolean") {
3404
3050
  return String(defaultValue);
3405
3051
  }
3406
3052
  if (defaultValue === null) {
3407
3053
  return "null";
3408
3054
  }
3409
3055
  if (Array.isArray(defaultValue)) {
3410
- return `[${defaultValue.map((item) => this.generateDefaultValue(item)).join(", ")}]`;
3056
+ const items = defaultValue.map((item) => typeof item === "string" ? `'${this.escapeString(item)}'` : String(item));
3057
+ return `[${items.join(", ")}]`;
3411
3058
  }
3412
3059
  if (typeof defaultValue === "object") {
3413
- const entries = Object.entries(defaultValue).map(([key, value]) => `${emitObjectKey(key)}: ${this.generateDefaultValue(value)}`).join(", ");
3060
+ const entries = Object.entries(defaultValue).map(([key, value]) => {
3061
+ const val = typeof value === "string" ? `'${this.escapeString(value)}'` : String(value);
3062
+ return `${key}: ${val}`;
3063
+ }).join(", ");
3414
3064
  return `{ ${entries} }`;
3415
3065
  }
3416
3066
  return "undefined";
3417
3067
  }
3418
- };
3419
- function stripRegexDelimiters(pattern) {
3420
- return pattern.replace(/^\/|\/$/g, "");
3421
- }
3422
- __name(stripRegexDelimiters, "stripRegexDelimiters");
3423
- function emitEnumMember(value) {
3424
- if (typeof value === "string") {
3425
- return quoteLiteral(value);
3068
+ escapeString(str2) {
3069
+ return str2.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/\n/g, "\\n");
3426
3070
  }
3427
- if (typeof value === "boolean" || typeof value === "number" && Number.isFinite(value)) {
3428
- return String(value);
3071
+ escapeRegex(pattern) {
3072
+ const cleaned = pattern.replace(/^\/|\/$/g, "");
3073
+ return cleaned.replace(/\\/g, "\\\\");
3429
3074
  }
3430
- return quoteLiteral(JSON.stringify(value) ?? String(value));
3431
- }
3432
- __name(emitEnumMember, "emitEnumMember");
3075
+ };
3433
3076
 
3434
3077
  // src/lib/zod-schema.generator.ts
3435
3078
  var ZodSchemaGenerator = class {
@@ -3447,7 +3090,7 @@ var ZodSchemaGenerator = class {
3447
3090
  this.schemaBuilder = new ZodSchemaBuilder(spec, config, options);
3448
3091
  }
3449
3092
  async generateParametersValidator(parameters, operationName, suffix) {
3450
- const properties = /* @__PURE__ */ new Map();
3093
+ const properties = {};
3451
3094
  const requiredFields = [];
3452
3095
  for (const param of parameters) {
3453
3096
  const schema2 = this.resolveParameterSchema(param);
@@ -3456,7 +3099,7 @@ var ZodSchemaGenerator = class {
3456
3099
  coerce: this.shouldCoerce(param.in),
3457
3100
  strict: this.isStrict(param.in)
3458
3101
  });
3459
- properties.set(param.name, zodSchema);
3102
+ properties[param.name] = zodSchema;
3460
3103
  if (param.required) {
3461
3104
  requiredFields.push(param.name);
3462
3105
  }
@@ -3547,12 +3190,10 @@ var ZodSchemaGenerator = class {
3547
3190
  return statements;
3548
3191
  }
3549
3192
  generateObjectValidator(name, properties) {
3550
- if (properties.size === 0) {
3193
+ if (Object.keys(properties).length === 0) {
3551
3194
  return `export const ${name} = z.object({});`;
3552
3195
  }
3553
- const props = [
3554
- ...properties
3555
- ].map(([key, schema2]) => ` ${emitObjectKey(key)}: ${schema2}`).join(",\n");
3196
+ const props = Object.entries(properties).map(([key, schema2]) => ` "${key}": ${schema2}`).join(",\n");
3556
3197
  const statements = [
3557
3198
  `export const ${name} = z.object({`,
3558
3199
  props,
@@ -3648,6 +3289,7 @@ var ZodIndexGenerator = class {
3648
3289
  });
3649
3290
  });
3650
3291
  sourceFile.formatText();
3292
+ sourceFile.saveSync();
3651
3293
  }
3652
3294
  };
3653
3295
 
@@ -3695,36 +3337,31 @@ var ZodGenerator = class {
3695
3337
  this.onWarning?.("No API paths found in the specification");
3696
3338
  return;
3697
3339
  }
3698
- const controllerGroups = groupOperationsByController(paths, this.onWarning);
3699
- this.assertDistinctOperationNames(controllerGroups);
3340
+ const controllerGroups = this.groupPathsByController(paths);
3700
3341
  await Promise.all(Object.entries(controllerGroups).map(([validatorName, operations]) => {
3701
3342
  return this.generateValidatorFile(validatorName, operations, outputDir);
3702
3343
  }));
3703
3344
  this.indexGenerator.generateIndex(outputRoot);
3704
3345
  }
3705
- assertDistinctOperationNames(controllerGroups) {
3706
- const byName = /* @__PURE__ */ new Map();
3707
- for (const operations of Object.values(controllerGroups)) {
3708
- for (const operation of operations) {
3709
- const name = this.getOperationName(operation);
3710
- const existing = byName.get(name);
3711
- if (existing) {
3712
- existing.push(operation);
3713
- } else {
3714
- byName.set(name, [
3715
- operation
3716
- ]);
3346
+ groupPathsByController(paths) {
3347
+ const groups = {};
3348
+ paths.forEach((path3) => {
3349
+ let controllerName = "Default";
3350
+ if (path3.tags && path3.tags.length > 0) {
3351
+ controllerName = path3.tags[0];
3352
+ } else {
3353
+ const pathParts = path3.path.split("/").filter((p) => p && !p.startsWith("{"));
3354
+ if (pathParts.length > 1) {
3355
+ controllerName = pascalCase(pathParts[1]);
3717
3356
  }
3718
3357
  }
3719
- }
3720
- const collisions = [
3721
- ...byName.entries()
3722
- ].filter(([, operations]) => operations.length > 1);
3723
- if (collisions.length === 0) {
3724
- return;
3725
- }
3726
- const detail = collisions.map(([name, operations]) => `"${name}" from ${operations.map(describeOperation).join(" and ")}`).join("; ");
3727
- throw new DuplicateGeneratedNameError(`Operations map to the same zod validator name: ${detail}. Ensure each operationId maps to a unique name.`, collisions.map(([name]) => name), collisions.flatMap(([, operations]) => operations));
3358
+ controllerName = pascalCase(controllerName);
3359
+ if (!groups[controllerName]) {
3360
+ groups[controllerName] = [];
3361
+ }
3362
+ groups[controllerName].push(path3);
3363
+ });
3364
+ return groups;
3728
3365
  }
3729
3366
  async generateValidatorFile(validatorName, operations, outputDir) {
3730
3367
  const fileName = `${camelCase(validatorName)}.validator.ts`;
@@ -3741,6 +3378,7 @@ var ZodGenerator = class {
3741
3378
  if (_statements.length > 0) {
3742
3379
  sourceFile.formatText();
3743
3380
  sourceFile.insertText(0, ZOD_PLUGIN_GENERATOR_HEADER_COMMENT(validatorName));
3381
+ sourceFile.saveSync();
3744
3382
  } else {
3745
3383
  this.project.removeSourceFile(sourceFile);
3746
3384
  }
package/index.d.ts CHANGED
@@ -367,7 +367,7 @@ declare class ZodGenerator implements IPluginGenerator {
367
367
  private readonly onWarning?;
368
368
  constructor(context: PluginGeneratorContext, options?: ZodPluginOptions);
369
369
  generate(outputRoot: string): Promise<void>;
370
- private assertDistinctOperationNames;
370
+ private groupPathsByController;
371
371
  private generateValidatorFile;
372
372
  private addImports;
373
373
  private generateOperationValidators;
package/index.js CHANGED
@@ -4,238 +4,6 @@ var __name = (target, value) => __defProp(target, "name", { value, configurable:
4
4
  // src/lib/zod.generator.ts
5
5
  import * as path2 from "path";
6
6
 
7
- // ../../shared/src/errors.ts
8
- var NG_OPENAPI_ERROR_BRAND = "__ngOpenApiError";
9
- var ERROR_LINEAGE = /* @__PURE__ */ new WeakMap();
10
- var FALLBACK_LINEAGE = Object.freeze([
11
- "NgOpenApiError"
12
- ]);
13
- function registerError(cls, lineage) {
14
- ERROR_LINEAGE.set(cls, Object.freeze([
15
- ...lineage
16
- ]));
17
- return cls;
18
- }
19
- __name(registerError, "registerError");
20
- function inheritedLineage(cls) {
21
- for (let current = cls; typeof current === "function"; current = Object.getPrototypeOf(current)) {
22
- const lineage = ERROR_LINEAGE.get(current);
23
- if (lineage) {
24
- return lineage;
25
- }
26
- }
27
- return FALLBACK_LINEAGE;
28
- }
29
- __name(inheritedLineage, "inheritedLineage");
30
- var NgOpenApiError = class extends Error {
31
- static {
32
- __name(this, "NgOpenApiError");
33
- }
34
- /** The underlying error that caused this one, when there is one. */
35
- cause;
36
- constructor(message, cause) {
37
- super(message);
38
- const lineage = inheritedLineage(new.target);
39
- this.name = lineage[0];
40
- this.cause = cause;
41
- Object.defineProperty(this, NG_OPENAPI_ERROR_BRAND, {
42
- value: lineage,
43
- enumerable: false,
44
- writable: false,
45
- configurable: false
46
- });
47
- }
48
- /**
49
- * `message` and `name` are non-enumerable on Error, so the default
50
- * JSON.stringify dropped both — the least useful possible serialization for
51
- * something that exists to be logged.
52
- *
53
- * The payload is spread rather than enumerated: `source`, `issues`,
54
- * `operation`, `names` and `placeholders` are why these classes are typed
55
- * in the first place, and listing fields by hand silently drops whichever
56
- * ones a later subclass adds.
57
- */
58
- toJSON() {
59
- const cause = this.cause instanceof Error ? this.cause.message : this.cause;
60
- return {
61
- name: this.name,
62
- message: this.message,
63
- ...cause === void 0 ? {} : {
64
- cause
65
- },
66
- // Own enumerable properties: the brand is deliberately not one.
67
- ...Object.fromEntries(Object.entries(this).filter(([key]) => key !== "cause"))
68
- };
69
- }
70
- /**
71
- * Recognizes branded errors from another bundled copy of this module, so
72
- * `error instanceof SpecLoadError` works for a plugin-thrown error too.
73
- * The prototype chain is checked first, so a caller's own subclass of these
74
- * classes still matches even though it carries no lineage entry.
75
- *
76
- * Never throws and never runs foreign code: both reflective reads sit
77
- * inside the try, because a Proxy traps `getPrototypeOf` just as readily as
78
- * `getOwnPropertyDescriptor`.
79
- */
80
- static [Symbol.hasInstance](value) {
81
- if (typeof value !== "object" || value === null) {
82
- return false;
83
- }
84
- try {
85
- if (Object.prototype.isPrototypeOf.call(this.prototype, value)) {
86
- return true;
87
- }
88
- const expected = ERROR_LINEAGE.get(this)?.[0];
89
- if (expected === void 0) {
90
- return false;
91
- }
92
- const descriptor = Object.getOwnPropertyDescriptor(value, NG_OPENAPI_ERROR_BRAND);
93
- if (!descriptor || descriptor.enumerable || !("value" in descriptor)) {
94
- return false;
95
- }
96
- return Array.isArray(descriptor.value) && descriptor.value.includes(expected);
97
- } catch {
98
- return false;
99
- }
100
- }
101
- };
102
- registerError(NgOpenApiError, [
103
- "NgOpenApiError"
104
- ]);
105
- var SpecLoadError = class extends NgOpenApiError {
106
- static {
107
- __name(this, "SpecLoadError");
108
- }
109
- /** The file path or URL that failed to load. */
110
- source;
111
- constructor(message, source, cause) {
112
- super(message, cause);
113
- this.source = source;
114
- }
115
- };
116
- registerError(SpecLoadError, [
117
- "SpecLoadError",
118
- "NgOpenApiError"
119
- ]);
120
- var SpecParseError = class extends NgOpenApiError {
121
- static {
122
- __name(this, "SpecParseError");
123
- }
124
- /** The file path or URL the content came from, when known. */
125
- source;
126
- constructor(message, source, cause) {
127
- super(message, cause);
128
- this.source = source;
129
- }
130
- };
131
- registerError(SpecParseError, [
132
- "SpecParseError",
133
- "NgOpenApiError"
134
- ]);
135
- function describeOperation(operation) {
136
- const location = `(${operation.method}) ${operation.path}`;
137
- return operation.operationId ? `${operation.operationId} (${location})` : location;
138
- }
139
- __name(describeOperation, "describeOperation");
140
- function captureOperation(operation) {
141
- return Object.freeze({
142
- operationId: operation.operationId,
143
- method: operation.method,
144
- path: operation.path
145
- });
146
- }
147
- __name(captureOperation, "captureOperation");
148
- var InvalidIdentifierError = class extends NgOpenApiError {
149
- static {
150
- __name(this, "InvalidIdentifierError");
151
- }
152
- /** The rejected name, verbatim; absent when no name could be derived. */
153
- identifier;
154
- /** The operation whose name was being derived. */
155
- operation;
156
- constructor(message, operation, identifier) {
157
- super(message);
158
- this.operation = captureOperation(operation);
159
- this.identifier = identifier;
160
- }
161
- };
162
- registerError(InvalidIdentifierError, [
163
- "InvalidIdentifierError",
164
- "NgOpenApiError"
165
- ]);
166
- var DuplicateGeneratedNameError = class extends NgOpenApiError {
167
- static {
168
- __name(this, "DuplicateGeneratedNameError");
169
- }
170
- /** The colliding generated names. */
171
- names;
172
- /** The operations that produced them, when known. */
173
- operations;
174
- constructor(message, names, operations = []) {
175
- super(message);
176
- this.names = Object.freeze([
177
- ...names
178
- ]);
179
- this.operations = Object.freeze(operations.map(captureOperation));
180
- }
181
- };
182
- registerError(DuplicateGeneratedNameError, [
183
- "DuplicateGeneratedNameError",
184
- "NgOpenApiError"
185
- ]);
186
- var UnresolvedPathTemplateError = class extends NgOpenApiError {
187
- static {
188
- __name(this, "UnresolvedPathTemplateError");
189
- }
190
- /** The path as written in the spec. */
191
- path;
192
- /** Placeholder names with no declared parameter. */
193
- placeholders;
194
- constructor(message, path3, placeholders) {
195
- super(message);
196
- this.path = path3;
197
- this.placeholders = Object.freeze([
198
- ...placeholders
199
- ]);
200
- }
201
- };
202
- registerError(UnresolvedPathTemplateError, [
203
- "UnresolvedPathTemplateError",
204
- "NgOpenApiError"
205
- ]);
206
- var ConfigValidationError = class extends NgOpenApiError {
207
- static {
208
- __name(this, "ConfigValidationError");
209
- }
210
- issues;
211
- constructor(issues) {
212
- super(`Invalid ng-openapi configuration:
213
- ${issues.map((issue) => ` - ${issue}`).join("\n")}`);
214
- this.issues = Object.freeze([
215
- ...issues
216
- ]);
217
- }
218
- };
219
- registerError(ConfigValidationError, [
220
- "ConfigValidationError",
221
- "NgOpenApiError"
222
- ]);
223
- var ConfigLoadError = class extends NgOpenApiError {
224
- static {
225
- __name(this, "ConfigLoadError");
226
- }
227
- /** Path of the config file that failed to load. */
228
- source;
229
- constructor(message, source, cause) {
230
- super(message, cause);
231
- this.source = source;
232
- }
233
- };
234
- registerError(ConfigLoadError, [
235
- "ConfigLoadError",
236
- "NgOpenApiError"
237
- ]);
238
-
239
7
  // ../../../node_modules/js-yaml/dist/js-yaml.mjs
240
8
  function isNothing(subject) {
241
9
  return typeof subject === "undefined" || subject === null;
@@ -2945,69 +2713,16 @@ var CONTENT_TYPES = {
2945
2713
  JSON: "application/json"
2946
2714
  };
2947
2715
 
2948
- // ../../shared/src/emit/literal.emit.ts
2949
- function quoteLiteral(value) {
2950
- return `'${escapeSingleQuoted(value)}'`;
2951
- }
2952
- __name(quoteLiteral, "quoteLiteral");
2953
- function escapeSingleQuoted(value) {
2954
- return value.replace(/[\\']/g, (char) => `\\${char}`).replace(/\r/g, "\\r").replace(/\n/g, "\\n");
2955
- }
2956
- __name(escapeSingleQuoted, "escapeSingleQuoted");
2957
- function emitObjectKey(name, quoteStyle = "double") {
2958
- const quoted = quoteStyle === "single" ? quoteLiteral(name) : `"${escapeDoubleQuoted(name)}"`;
2959
- return name === "__proto__" ? `[${quoted}]` : quoted;
2960
- }
2961
- __name(emitObjectKey, "emitObjectKey");
2962
- function escapeDoubleQuoted(value) {
2963
- return value.replace(/[\\"]/g, (char) => `\\${char}`).replace(/\r/g, "\\r").replace(/\n/g, "\\n");
2964
- }
2965
- __name(escapeDoubleQuoted, "escapeDoubleQuoted");
2966
-
2967
2716
  // ../../shared/src/utils/string.utils.ts
2968
- var IDENTIFIER_SEPARATORS = /(?:_|[^\p{ID_Continue}$])+(.)?/gu;
2969
- var INVALID_IDENTIFIER_START = /^[^\p{ID_Start}$_]/u;
2970
- function toIdentifier(converted) {
2971
- if (converted === "") {
2972
- return "_";
2973
- }
2974
- return converted.replace(INVALID_IDENTIFIER_START, (char) => `_${char}`);
2975
- }
2976
- __name(toIdentifier, "toIdentifier");
2977
2717
  function camelCase(str2) {
2978
- const converted = str2.replace(IDENTIFIER_SEPARATORS, (_, char) => char ? char.toUpperCase() : "").replace(/^./u, (char) => char.toLowerCase());
2979
- return toIdentifier(converted);
2718
+ return str2.replace(/[-_.\s]+(.)?/g, (_, char) => char ? char.toUpperCase() : "").replace(/^./, (char) => char.toLowerCase());
2980
2719
  }
2981
2720
  __name(camelCase, "camelCase");
2982
2721
  function pascalCase(str2) {
2983
- const converted = str2.replace(IDENTIFIER_SEPARATORS, (_, char) => char ? char.toUpperCase() : "").replace(/^./u, (char) => char.toUpperCase());
2984
- return toIdentifier(converted);
2722
+ return str2.replace(/[-_.\s]+(.)?/g, (_, char) => char ? char.toUpperCase() : "").replace(/^./, (char) => char.toUpperCase());
2985
2723
  }
2986
2724
  __name(pascalCase, "pascalCase");
2987
2725
 
2988
- // ../../shared/src/utils/functions/argument-names.ts
2989
- var SERVICE_ARGUMENT_PROFILE = Object.freeze({
2990
- reserved: Object.freeze([
2991
- "observe",
2992
- "options",
2993
- "url",
2994
- "params",
2995
- "headers",
2996
- "formData",
2997
- "formBody"
2998
- ]),
2999
- bindsRequestBody: true
3000
- });
3001
- var RESOURCE_ARGUMENT_PROFILE = Object.freeze({
3002
- reserved: Object.freeze([
3003
- "resourceOptions",
3004
- "requestOptions",
3005
- "params",
3006
- "headers"
3007
- ]),
3008
- bindsRequestBody: false
3009
- });
3010
-
3011
2726
  // ../../shared/src/utils/project.utils.ts
3012
2727
  function listGeneratedFileNames(project, directoryPath, suffix) {
3013
2728
  const directory = project.getDirectory(directoryPath);
@@ -3018,65 +2733,6 @@ function listGeneratedFileNames(project, directoryPath, suffix) {
3018
2733
  }
3019
2734
  __name(listGeneratedFileNames, "listGeneratedFileNames");
3020
2735
 
3021
- // ../../shared/src/utils/functions/controller-groups.ts
3022
- function groupOperationsByController(operations, onWarning) {
3023
- const groups = {};
3024
- const controllerByFold = /* @__PURE__ */ new Map();
3025
- const tagSpellings = /* @__PURE__ */ new Map();
3026
- const namelessTags = /* @__PURE__ */ new Set();
3027
- operations.forEach((operation) => {
3028
- const tag = operation.tags?.[0];
3029
- let rawName = "Default";
3030
- if (tag !== void 0) {
3031
- rawName = tag;
3032
- } else {
3033
- const pathParts = operation.path.split("/").filter((part) => part && !part.startsWith("{"));
3034
- if (pathParts.length > 1) {
3035
- rawName = pathParts[1];
3036
- }
3037
- }
3038
- const sanitized = pascalCase(rawName);
3039
- const isNameless = !/\p{L}/u.test(sanitized);
3040
- const candidate = isNameless ? "Default" : sanitized;
3041
- const fold = candidate.toLowerCase();
3042
- const controllerName = controllerByFold.get(fold) ?? candidate;
3043
- controllerByFold.set(fold, controllerName);
3044
- if (tag !== void 0 && isNameless) {
3045
- namelessTags.add(tag);
3046
- } else if (tag !== void 0) {
3047
- const spellings = tagSpellings.get(controllerName) ?? /* @__PURE__ */ new Set();
3048
- spellings.add(tag);
3049
- tagSpellings.set(controllerName, spellings);
3050
- }
3051
- if (!groups[controllerName]) {
3052
- groups[controllerName] = [];
3053
- }
3054
- groups[controllerName].push(operation);
3055
- });
3056
- for (const tag of namelessTags) {
3057
- onWarning?.(`Tag "${tag}" contains no characters usable in a name \u2014 its operations are generated into the "Default" controller. Rename the tag to give them a file of their own.`);
3058
- }
3059
- for (const [controllerName, spellings] of tagSpellings) {
3060
- if (spellings.size > 1) {
3061
- onWarning?.(`Tags ${[
3062
- ...spellings
3063
- ].map((name) => `"${name}"`).join(" and ")} all map to the controller "${controllerName}" \u2014 their operations are generated into one file. Rename one tag to keep them apart.`);
3064
- }
3065
- }
3066
- return groups;
3067
- }
3068
- __name(groupOperationsByController, "groupOperationsByController");
3069
-
3070
- // ../../shared/src/utils/functions/method-names.ts
3071
- var RESERVED_MEMBER_NAMES = Object.freeze([
3072
- "constructor",
3073
- "httpClient",
3074
- "basePath",
3075
- "clientContextToken",
3076
- "createContextWithClientId"
3077
- ]);
3078
- var RESERVED_MEMBER_SET = new Set(RESERVED_MEMBER_NAMES);
3079
-
3080
2736
  // ../../shared/src/config/constants.ts
3081
2737
  var disableLinting = `// @ts-nocheck
3082
2738
  /* eslint-disable */
@@ -3176,14 +2832,14 @@ var ZodSchemaBuilder = class {
3176
2832
  } else if (!buildOptions.required) {
3177
2833
  zodSchema = `${zodSchema}.optional()`;
3178
2834
  }
3179
- if (typeof schema2.description === "string" && schema2.description) {
3180
- zodSchema = `${zodSchema}.describe('${escapeSingleQuoted(schema2.description)}')`;
2835
+ if (schema2.description) {
2836
+ zodSchema = `${zodSchema}.describe('${this.escapeString(schema2.description)}')`;
3181
2837
  }
3182
2838
  return zodSchema;
3183
2839
  }
3184
2840
  async buildStringSchema(schema2, buildOptions) {
3185
2841
  if (schema2.enum && schema2.enum.every((v) => typeof v === "string")) {
3186
- const enumValues = schema2.enum.map((v) => emitEnumMember(v)).join(", ");
2842
+ const enumValues = schema2.enum.map((v) => `'${this.escapeString(String(v))}'`).join(", ");
3187
2843
  return `z.enum([${enumValues}])`;
3188
2844
  }
3189
2845
  if (schema2.format) {
@@ -3217,14 +2873,15 @@ var ZodSchemaBuilder = class {
3217
2873
  }
3218
2874
  }
3219
2875
  let zodString = buildOptions.coerce ? "z.coerce.string()" : "z.string()";
3220
- if (typeof schema2.minLength === "number" && Number.isFinite(schema2.minLength)) {
2876
+ if (schema2.minLength !== void 0) {
3221
2877
  zodString += `.min(${schema2.minLength})`;
3222
2878
  }
3223
- if (typeof schema2.maxLength === "number" && Number.isFinite(schema2.maxLength)) {
2879
+ if (schema2.maxLength !== void 0) {
3224
2880
  zodString += `.max(${schema2.maxLength})`;
3225
2881
  }
3226
- if (typeof schema2.pattern === "string") {
3227
- zodString += `.regex(new RegExp(${quoteLiteral(stripRegexDelimiters(schema2.pattern))}))`;
2882
+ if (schema2.pattern) {
2883
+ const escapedPattern = this.escapeRegex(schema2.pattern);
2884
+ zodString += `.regex(new RegExp('${escapedPattern}'))`;
3228
2885
  }
3229
2886
  return zodString;
3230
2887
  }
@@ -3237,13 +2894,13 @@ var ZodSchemaBuilder = class {
3237
2894
  return `z.union([${literals}])`;
3238
2895
  }
3239
2896
  let zodNumber = buildOptions.coerce ? "z.coerce.number()" : "z.number()";
3240
- if (typeof schema2.minimum === "number" && Number.isFinite(schema2.minimum)) {
2897
+ if (schema2.minimum !== void 0) {
3241
2898
  zodNumber += `.min(${schema2.minimum})`;
3242
2899
  }
3243
- if (typeof schema2.maximum === "number" && Number.isFinite(schema2.maximum)) {
2900
+ if (schema2.maximum !== void 0) {
3244
2901
  zodNumber += `.max(${schema2.maximum})`;
3245
2902
  }
3246
- if (typeof schema2.multipleOf === "number" && Number.isFinite(schema2.multipleOf)) {
2903
+ if (schema2.multipleOf !== void 0) {
3247
2904
  zodNumber += `.multipleOf(${schema2.multipleOf})`;
3248
2905
  }
3249
2906
  if (schema2.type === "integer") {
@@ -3270,10 +2927,10 @@ var ZodSchemaBuilder = class {
3270
2927
  required: true
3271
2928
  });
3272
2929
  let zodArray = `z.array(${itemSchema})`;
3273
- if (typeof schema2.minItems === "number" && Number.isFinite(schema2.minItems)) {
2930
+ if (schema2.minItems !== void 0) {
3274
2931
  zodArray += `.min(${schema2.minItems})`;
3275
2932
  }
3276
- if (typeof schema2.maxItems === "number" && Number.isFinite(schema2.maxItems)) {
2933
+ if (schema2.maxItems !== void 0) {
3277
2934
  zodArray += `.max(${schema2.maxItems})`;
3278
2935
  }
3279
2936
  return zodArray;
@@ -3317,7 +2974,7 @@ var ZodSchemaBuilder = class {
3317
2974
  ...buildOptions,
3318
2975
  required: isRequired
3319
2976
  });
3320
- properties.push(` ${emitObjectKey(propName)}: ${propZodSchema}`);
2977
+ properties.push(` "${propName}": ${propZodSchema}`);
3321
2978
  }
3322
2979
  let objectSchema = `z.object({
3323
2980
  ${properties.join(",\n")}
@@ -3351,51 +3008,37 @@ ${properties.join(",\n")}
3351
3008
  }
3352
3009
  return schema2.type || "any";
3353
3010
  }
3354
- /**
3355
- * A default value as a zod `.default(...)` literal.
3356
- *
3357
- * Recursive, because a default is arbitrary JSON: object keys are spec text
3358
- * and went into the literal raw (`{ my-key: 1 }` is a syntax error, a
3359
- * `__proto__` key is the setter), and nested values went through
3360
- * `String()`, which emits `[object Object]` into source. Not
3361
- * `emitEnumMember`: that helper serializes an unknown value as a *string*
3362
- * because a z.enum member must be one, which turned `default: ["x", null]`
3363
- * into `['x', 'null']`.
3364
- */
3365
3011
  generateDefaultValue(defaultValue) {
3366
3012
  if (typeof defaultValue === "string") {
3367
- return quoteLiteral(defaultValue);
3013
+ return `'${this.escapeString(defaultValue)}'`;
3368
3014
  }
3369
- if (typeof defaultValue === "boolean" || typeof defaultValue === "number" && Number.isFinite(defaultValue)) {
3015
+ if (typeof defaultValue === "number" || typeof defaultValue === "boolean") {
3370
3016
  return String(defaultValue);
3371
3017
  }
3372
3018
  if (defaultValue === null) {
3373
3019
  return "null";
3374
3020
  }
3375
3021
  if (Array.isArray(defaultValue)) {
3376
- return `[${defaultValue.map((item) => this.generateDefaultValue(item)).join(", ")}]`;
3022
+ const items = defaultValue.map((item) => typeof item === "string" ? `'${this.escapeString(item)}'` : String(item));
3023
+ return `[${items.join(", ")}]`;
3377
3024
  }
3378
3025
  if (typeof defaultValue === "object") {
3379
- const entries = Object.entries(defaultValue).map(([key, value]) => `${emitObjectKey(key)}: ${this.generateDefaultValue(value)}`).join(", ");
3026
+ const entries = Object.entries(defaultValue).map(([key, value]) => {
3027
+ const val = typeof value === "string" ? `'${this.escapeString(value)}'` : String(value);
3028
+ return `${key}: ${val}`;
3029
+ }).join(", ");
3380
3030
  return `{ ${entries} }`;
3381
3031
  }
3382
3032
  return "undefined";
3383
3033
  }
3384
- };
3385
- function stripRegexDelimiters(pattern) {
3386
- return pattern.replace(/^\/|\/$/g, "");
3387
- }
3388
- __name(stripRegexDelimiters, "stripRegexDelimiters");
3389
- function emitEnumMember(value) {
3390
- if (typeof value === "string") {
3391
- return quoteLiteral(value);
3034
+ escapeString(str2) {
3035
+ return str2.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/\n/g, "\\n");
3392
3036
  }
3393
- if (typeof value === "boolean" || typeof value === "number" && Number.isFinite(value)) {
3394
- return String(value);
3037
+ escapeRegex(pattern) {
3038
+ const cleaned = pattern.replace(/^\/|\/$/g, "");
3039
+ return cleaned.replace(/\\/g, "\\\\");
3395
3040
  }
3396
- return quoteLiteral(JSON.stringify(value) ?? String(value));
3397
- }
3398
- __name(emitEnumMember, "emitEnumMember");
3041
+ };
3399
3042
 
3400
3043
  // src/lib/zod-schema.generator.ts
3401
3044
  var ZodSchemaGenerator = class {
@@ -3413,7 +3056,7 @@ var ZodSchemaGenerator = class {
3413
3056
  this.schemaBuilder = new ZodSchemaBuilder(spec, config, options);
3414
3057
  }
3415
3058
  async generateParametersValidator(parameters, operationName, suffix) {
3416
- const properties = /* @__PURE__ */ new Map();
3059
+ const properties = {};
3417
3060
  const requiredFields = [];
3418
3061
  for (const param of parameters) {
3419
3062
  const schema2 = this.resolveParameterSchema(param);
@@ -3422,7 +3065,7 @@ var ZodSchemaGenerator = class {
3422
3065
  coerce: this.shouldCoerce(param.in),
3423
3066
  strict: this.isStrict(param.in)
3424
3067
  });
3425
- properties.set(param.name, zodSchema);
3068
+ properties[param.name] = zodSchema;
3426
3069
  if (param.required) {
3427
3070
  requiredFields.push(param.name);
3428
3071
  }
@@ -3513,12 +3156,10 @@ var ZodSchemaGenerator = class {
3513
3156
  return statements;
3514
3157
  }
3515
3158
  generateObjectValidator(name, properties) {
3516
- if (properties.size === 0) {
3159
+ if (Object.keys(properties).length === 0) {
3517
3160
  return `export const ${name} = z.object({});`;
3518
3161
  }
3519
- const props = [
3520
- ...properties
3521
- ].map(([key, schema2]) => ` ${emitObjectKey(key)}: ${schema2}`).join(",\n");
3162
+ const props = Object.entries(properties).map(([key, schema2]) => ` "${key}": ${schema2}`).join(",\n");
3522
3163
  const statements = [
3523
3164
  `export const ${name} = z.object({`,
3524
3165
  props,
@@ -3614,6 +3255,7 @@ var ZodIndexGenerator = class {
3614
3255
  });
3615
3256
  });
3616
3257
  sourceFile.formatText();
3258
+ sourceFile.saveSync();
3617
3259
  }
3618
3260
  };
3619
3261
 
@@ -3661,36 +3303,31 @@ var ZodGenerator = class {
3661
3303
  this.onWarning?.("No API paths found in the specification");
3662
3304
  return;
3663
3305
  }
3664
- const controllerGroups = groupOperationsByController(paths, this.onWarning);
3665
- this.assertDistinctOperationNames(controllerGroups);
3306
+ const controllerGroups = this.groupPathsByController(paths);
3666
3307
  await Promise.all(Object.entries(controllerGroups).map(([validatorName, operations]) => {
3667
3308
  return this.generateValidatorFile(validatorName, operations, outputDir);
3668
3309
  }));
3669
3310
  this.indexGenerator.generateIndex(outputRoot);
3670
3311
  }
3671
- assertDistinctOperationNames(controllerGroups) {
3672
- const byName = /* @__PURE__ */ new Map();
3673
- for (const operations of Object.values(controllerGroups)) {
3674
- for (const operation of operations) {
3675
- const name = this.getOperationName(operation);
3676
- const existing = byName.get(name);
3677
- if (existing) {
3678
- existing.push(operation);
3679
- } else {
3680
- byName.set(name, [
3681
- operation
3682
- ]);
3312
+ groupPathsByController(paths) {
3313
+ const groups = {};
3314
+ paths.forEach((path3) => {
3315
+ let controllerName = "Default";
3316
+ if (path3.tags && path3.tags.length > 0) {
3317
+ controllerName = path3.tags[0];
3318
+ } else {
3319
+ const pathParts = path3.path.split("/").filter((p) => p && !p.startsWith("{"));
3320
+ if (pathParts.length > 1) {
3321
+ controllerName = pascalCase(pathParts[1]);
3683
3322
  }
3684
3323
  }
3685
- }
3686
- const collisions = [
3687
- ...byName.entries()
3688
- ].filter(([, operations]) => operations.length > 1);
3689
- if (collisions.length === 0) {
3690
- return;
3691
- }
3692
- const detail = collisions.map(([name, operations]) => `"${name}" from ${operations.map(describeOperation).join(" and ")}`).join("; ");
3693
- throw new DuplicateGeneratedNameError(`Operations map to the same zod validator name: ${detail}. Ensure each operationId maps to a unique name.`, collisions.map(([name]) => name), collisions.flatMap(([, operations]) => operations));
3324
+ controllerName = pascalCase(controllerName);
3325
+ if (!groups[controllerName]) {
3326
+ groups[controllerName] = [];
3327
+ }
3328
+ groups[controllerName].push(path3);
3329
+ });
3330
+ return groups;
3694
3331
  }
3695
3332
  async generateValidatorFile(validatorName, operations, outputDir) {
3696
3333
  const fileName = `${camelCase(validatorName)}.validator.ts`;
@@ -3707,6 +3344,7 @@ var ZodGenerator = class {
3707
3344
  if (_statements.length > 0) {
3708
3345
  sourceFile.formatText();
3709
3346
  sourceFile.insertText(0, ZOD_PLUGIN_GENERATOR_HEADER_COMMENT(validatorName));
3347
+ sourceFile.saveSync();
3710
3348
  } else {
3711
3349
  this.project.removeSourceFile(sourceFile);
3712
3350
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ng-openapi/zod",
3
- "version": "0.1.3-pr-127-fix-125-sanitize-generated-identifiers-9082a48.0",
3
+ "version": "0.1.3",
4
4
  "description": "Zod validation plugin for ng-openapi - Generate Zod schemas from OpenAPI specifications",
5
5
  "keywords": [
6
6
  "angular",