@warlock.js/core 5.27.0 → 5.28.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/CHANGELOG.md +11 -0
- package/esm/cli/commands/openapi-generator.action.mjs +1 -1
- package/esm/cli/commands/openapi-generator.action.mjs.map +1 -1
- package/esm/cli/commands/postman-generator.action.mjs +47 -0
- package/esm/cli/commands/postman-generator.action.mjs.map +1 -0
- package/esm/cli/commands/postman-generator.command.mjs +43 -0
- package/esm/cli/commands/postman-generator.command.mjs.map +1 -0
- package/esm/cli/framework-cli-commands.mjs +2 -0
- package/esm/cli/framework-cli-commands.mjs.map +1 -1
- package/esm/http/middleware/inject-request-context.d.mts.map +1 -1
- package/esm/http/middleware/inject-request-context.mjs +29 -3
- package/esm/http/middleware/inject-request-context.mjs.map +1 -1
- package/esm/http/request.d.mts +2 -2
- package/esm/http/request.d.mts.map +1 -1
- package/esm/index.d.mts +5 -2
- package/esm/index.mjs +4 -2
- package/esm/openapi/development-openapi-provider.d.mts +12 -1
- package/esm/openapi/development-openapi-provider.d.mts.map +1 -1
- package/esm/openapi/development-openapi-provider.mjs +15 -1
- package/esm/openapi/development-openapi-provider.mjs.map +1 -1
- package/esm/openapi/index.d.mts +5 -2
- package/esm/openapi/index.mjs +3 -1
- package/esm/openapi/postman/build-request-body.mjs +86 -0
- package/esm/openapi/postman/build-request-body.mjs.map +1 -0
- package/esm/openapi/postman/build-request-url.mjs +85 -0
- package/esm/openapi/postman/build-request-url.mjs.map +1 -0
- package/esm/openapi/postman/build-saved-responses.mjs +60 -0
- package/esm/openapi/postman/build-saved-responses.mjs.map +1 -0
- package/esm/openapi/postman/example-from-schema.d.mts +17 -0
- package/esm/openapi/postman/example-from-schema.d.mts.map +1 -0
- package/esm/openapi/postman/example-from-schema.mjs +92 -0
- package/esm/openapi/postman/example-from-schema.mjs.map +1 -0
- package/esm/openapi/postman/http-status-text.mjs +31 -0
- package/esm/openapi/postman/http-status-text.mjs.map +1 -0
- package/esm/openapi/postman/index.d.mts +3 -0
- package/esm/openapi/postman/openapi-to-postman-collection.d.mts +22 -0
- package/esm/openapi/postman/openapi-to-postman-collection.d.mts.map +1 -0
- package/esm/openapi/postman/openapi-to-postman-collection.mjs +109 -0
- package/esm/openapi/postman/openapi-to-postman-collection.mjs.map +1 -0
- package/esm/openapi/postman/postman-types.d.mts +119 -0
- package/esm/openapi/postman/postman-types.d.mts.map +1 -0
- package/esm/openapi/postman/resolve-operation-auth.mjs +51 -0
- package/esm/openapi/postman/resolve-operation-auth.mjs.map +1 -0
- package/esm/openapi/postman/schema-refs.d.mts +7 -0
- package/esm/openapi/postman/schema-refs.d.mts.map +1 -0
- package/esm/openapi/postman/schema-refs.mjs +41 -0
- package/esm/openapi/postman/schema-refs.mjs.map +1 -0
- package/esm/openapi/postman/uuid-v5.mjs +29 -0
- package/esm/openapi/postman/uuid-v5.mjs.map +1 -0
- package/esm/resource/resource.d.mts.map +1 -1
- package/esm/resource/resource.mjs +2 -4
- package/esm/resource/resource.mjs.map +1 -1
- package/esm/restful/restful.d.mts +5 -5
- package/esm/restful/restful.d.mts.map +1 -1
- package/llms-full.txt +29 -1
- package/llms.txt +1 -1
- package/package.json +12 -12
- package/skills/generate-openapi/SKILL.md +29 -1
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
//#region ../core/src/openapi/postman/postman-types.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* The slice of the Postman Collection Format v2.1.0 the converter emits.
|
|
4
|
+
* Schema: https://schema.getpostman.com/json/collection/v2.1.0/collection.json
|
|
5
|
+
*/
|
|
6
|
+
type PostmanVariable = {
|
|
7
|
+
key: string;
|
|
8
|
+
value: string;
|
|
9
|
+
type?: "string";
|
|
10
|
+
description?: string;
|
|
11
|
+
};
|
|
12
|
+
type PostmanAuthEntry = {
|
|
13
|
+
key: string;
|
|
14
|
+
value: string;
|
|
15
|
+
type: "string";
|
|
16
|
+
};
|
|
17
|
+
type PostmanAuth = {
|
|
18
|
+
type: "noauth";
|
|
19
|
+
} | {
|
|
20
|
+
type: "bearer";
|
|
21
|
+
bearer: PostmanAuthEntry[];
|
|
22
|
+
};
|
|
23
|
+
type PostmanHeader = {
|
|
24
|
+
key: string;
|
|
25
|
+
value: string;
|
|
26
|
+
type?: "text";
|
|
27
|
+
description?: string;
|
|
28
|
+
disabled?: boolean;
|
|
29
|
+
};
|
|
30
|
+
type PostmanQueryParam = {
|
|
31
|
+
key: string;
|
|
32
|
+
value: string;
|
|
33
|
+
description?: string;
|
|
34
|
+
disabled?: boolean;
|
|
35
|
+
};
|
|
36
|
+
type PostmanUrl = {
|
|
37
|
+
raw: string;
|
|
38
|
+
host: string[];
|
|
39
|
+
path: string[];
|
|
40
|
+
variable?: PostmanVariable[];
|
|
41
|
+
query?: PostmanQueryParam[];
|
|
42
|
+
};
|
|
43
|
+
type PostmanFormParam = {
|
|
44
|
+
key: string;
|
|
45
|
+
value: string;
|
|
46
|
+
type: "text";
|
|
47
|
+
description?: string;
|
|
48
|
+
} | {
|
|
49
|
+
key: string;
|
|
50
|
+
type: "file";
|
|
51
|
+
src: string[];
|
|
52
|
+
description?: string;
|
|
53
|
+
};
|
|
54
|
+
type PostmanBody = {
|
|
55
|
+
mode: "raw";
|
|
56
|
+
raw: string;
|
|
57
|
+
options: {
|
|
58
|
+
raw: {
|
|
59
|
+
language: "json" | "text";
|
|
60
|
+
};
|
|
61
|
+
};
|
|
62
|
+
} | {
|
|
63
|
+
mode: "formdata";
|
|
64
|
+
formdata: PostmanFormParam[];
|
|
65
|
+
} | {
|
|
66
|
+
mode: "urlencoded";
|
|
67
|
+
urlencoded: {
|
|
68
|
+
key: string;
|
|
69
|
+
value: string;
|
|
70
|
+
type: "text";
|
|
71
|
+
}[];
|
|
72
|
+
};
|
|
73
|
+
type PostmanOriginalRequest = {
|
|
74
|
+
method: string;
|
|
75
|
+
header: PostmanHeader[];
|
|
76
|
+
body?: PostmanBody;
|
|
77
|
+
url: PostmanUrl;
|
|
78
|
+
};
|
|
79
|
+
type PostmanRequest = PostmanOriginalRequest & {
|
|
80
|
+
auth?: PostmanAuth;
|
|
81
|
+
description?: string;
|
|
82
|
+
};
|
|
83
|
+
type PostmanResponse = {
|
|
84
|
+
name: string;
|
|
85
|
+
originalRequest: PostmanOriginalRequest;
|
|
86
|
+
status: string;
|
|
87
|
+
code: number;
|
|
88
|
+
_postman_previewlanguage: "json" | "html" | "text";
|
|
89
|
+
header: PostmanHeader[];
|
|
90
|
+
body: string;
|
|
91
|
+
};
|
|
92
|
+
type PostmanRequestItem = {
|
|
93
|
+
name: string;
|
|
94
|
+
request: PostmanRequest;
|
|
95
|
+
response: PostmanResponse[];
|
|
96
|
+
};
|
|
97
|
+
type PostmanFolder = {
|
|
98
|
+
name: string;
|
|
99
|
+
item: PostmanItem[];
|
|
100
|
+
};
|
|
101
|
+
type PostmanItem = PostmanFolder | PostmanRequestItem;
|
|
102
|
+
type PostmanCollection = {
|
|
103
|
+
info: {
|
|
104
|
+
_postman_id: string;
|
|
105
|
+
name: string;
|
|
106
|
+
description?: string;
|
|
107
|
+
schema: "https://schema.getpostman.com/json/collection/v2.1.0/collection.json";
|
|
108
|
+
};
|
|
109
|
+
item: PostmanItem[];
|
|
110
|
+
auth?: PostmanAuth;
|
|
111
|
+
variable: PostmanVariable[];
|
|
112
|
+
};
|
|
113
|
+
type PostmanCollectionOptions = {
|
|
114
|
+
/** Collection name. Defaults to `info.title` of the document. */title?: string; /** Value of the `{{baseUrl}}` variable. Defaults to `servers[0].url`, else `http://localhost:3000`. */
|
|
115
|
+
baseUrl?: string;
|
|
116
|
+
};
|
|
117
|
+
//#endregion
|
|
118
|
+
export { PostmanAuth, PostmanAuthEntry, PostmanBody, PostmanCollection, PostmanCollectionOptions, PostmanFolder, PostmanFormParam, PostmanHeader, PostmanItem, PostmanOriginalRequest, PostmanQueryParam, PostmanRequest, PostmanRequestItem, PostmanResponse, PostmanUrl, PostmanVariable };
|
|
119
|
+
//# sourceMappingURL=postman-types.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"postman-types.d.mts","names":[],"sources":["../../../../../../../../core/src/openapi/postman/postman-types.ts"],"mappings":";;AAKA;;;KAAY,eAAA;EACV,GAAA;EACA,KAAA;EACA,IAAA;EACA,WAAA;AAAA;AAAA,KAGU,gBAAA;EAAqB,GAAA;EAAa,KAAA;EAAe,IAAA;AAAA;AAAA,KAEjD,WAAA;EAAgB,IAAA;AAAA;EAAqB,IAAA;EAAgB,MAAA,EAAQ,gBAAgB;AAAA;AAAA,KAE7E,aAAA;EACV,GAAA;EACA,KAAA;EACA,IAAA;EACA,WAAA;EACA,QAAA;AAAA;AAAA,KAGU,iBAAA;EACV,GAAA;EACA,KAAA;EACA,WAAA;EACA,QAAA;AAAA;AAAA,KAGU,UAAA;EACV,GAAA;EACA,IAAA;EACA,IAAA;EACA,QAAA,GAAW,eAAA;EACX,KAAA,GAAQ,iBAAiB;AAAA;AAAA,KAGf,gBAAA;EACN,GAAA;EAAa,KAAA;EAAe,IAAA;EAAc,WAAA;AAAA;EAC1C,GAAA;EAAa,IAAA;EAAc,GAAA;EAAe,WAAA;AAAA;AAAA,KAEpC,WAAA;EACN,IAAA;EAAa,GAAA;EAAa,OAAA;IAAW,GAAA;MAAO,QAAA;IAAA;EAAA;AAAA;EAC5C,IAAA;EAAkB,QAAA,EAAU,gBAAgB;AAAA;EAC5C,IAAA;EAAoB,UAAA;IAAc,GAAA;IAAa,KAAA;IAAe,IAAA;EAAA;AAAA;AAAA,KAExD,sBAAA;EACV,MAAA;EACA,MAAA,EAAQ,aAAA;EACR,IAAA,GAAO,WAAA;EACP,GAAA,EAAK,UAAA;AAAA;AAAA,KAGK,cAAA,GAAiB,sBAAA;EAC3B,IAAA,GAAO,WAAW;EAClB,WAAA;AAAA;AAAA,KAGU,eAAA;EACV,IAAA;EACA,eAAA,EAAiB,sBAAA;EACjB,MAAA;EACA,IAAA;EACA,wBAAA;EACA,MAAA,EAAQ,aAAa;EACrB,IAAA;AAAA;AAAA,KAGU,kBAAA;EACV,IAAA;EACA,OAAA,EAAS,cAAA;EACT,QAAA,EAAU,eAAe;AAAA;AAAA,KAGf,aAAA;EACV,IAAA;EACA,IAAA,EAAM,WAAW;AAAA;AAAA,KAGP,WAAA,GAAc,aAAA,GAAgB,kBAAkB;AAAA,KAEhD,iBAAA;EACV,IAAA;IACE,WAAA;IACA,IAAA;IACA,WAAA;IACA,MAAA;EAAA;EAEF,IAAA,EAAM,WAAA;EACN,IAAA,GAAO,WAAA;EACP,QAAA,EAAU,eAAA;AAAA;AAAA,KAGA,wBAAA;EA3CK,iEA6Cf,KAAA,WA1CU;EA4CV,OAAO;AAAA"}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
//#region ../core/src/openapi/postman/resolve-operation-auth.ts
|
|
2
|
+
/** The collection-level auth: a bearer token read from the `{{token}}` variable. */
|
|
3
|
+
function collectionBearerAuth() {
|
|
4
|
+
return {
|
|
5
|
+
type: "bearer",
|
|
6
|
+
bearer: [{
|
|
7
|
+
key: "token",
|
|
8
|
+
value: "{{token}}",
|
|
9
|
+
type: "string"
|
|
10
|
+
}]
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
function isBearer(scheme) {
|
|
14
|
+
return scheme?.type === "http" && scheme.scheme.toLowerCase() === "bearer";
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Whether the document declares an HTTP bearer scheme, which is what the collection-level
|
|
18
|
+
* auth stands for.
|
|
19
|
+
*/
|
|
20
|
+
function hasBearerScheme(components) {
|
|
21
|
+
return Object.values(components?.securitySchemes ?? {}).some(isBearer);
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* How one operation relates to the collection-level bearer auth.
|
|
25
|
+
*
|
|
26
|
+
* - No `security` (a public route): `noauth`, so the token is not sent.
|
|
27
|
+
* - A bearer requirement: inherits the collection auth.
|
|
28
|
+
* - Cookie-only: `noauth` plus a note, because Postman keeps cookies per domain instead of
|
|
29
|
+
* in collection auth.
|
|
30
|
+
*/
|
|
31
|
+
function resolveOperationAuth(operation, components) {
|
|
32
|
+
const bearerDocument = hasBearerScheme(components);
|
|
33
|
+
const schemes = components?.securitySchemes ?? {};
|
|
34
|
+
const names = (operation.security ?? []).flatMap((requirement) => Object.keys(requirement));
|
|
35
|
+
if (names.some((name) => isBearer(schemes[name]))) return {};
|
|
36
|
+
const cookies = names.flatMap((name) => {
|
|
37
|
+
const scheme = schemes[name];
|
|
38
|
+
return scheme?.type === "apiKey" && scheme.in === "cookie" ? [scheme.name] : [];
|
|
39
|
+
});
|
|
40
|
+
const auth = bearerDocument ? { auth: { type: "noauth" } } : {};
|
|
41
|
+
if (cookies.length === 0) return auth;
|
|
42
|
+
const cookieList = cookies.map((cookie) => `"${cookie}"`).join(", ");
|
|
43
|
+
return {
|
|
44
|
+
...auth,
|
|
45
|
+
note: `Authenticates with the ${cookieList} cookie. Postman keeps cookies per domain, so sign in against {{baseUrl}} first or add the cookie in the Cookies manager.`
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
//#endregion
|
|
50
|
+
export { collectionBearerAuth, hasBearerScheme, resolveOperationAuth };
|
|
51
|
+
//# sourceMappingURL=resolve-operation-auth.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resolve-operation-auth.mjs","names":[],"sources":["../../../../../../../../core/src/openapi/postman/resolve-operation-auth.ts"],"sourcesContent":["import type { OpenApiComponents, OpenApiOperation, OpenApiSecurityScheme } from \"../types\";\nimport type { PostmanAuth } from \"./postman-types\";\n\nexport type OperationAuth = {\n /** Set only when the operation must not inherit the collection auth. */\n auth?: PostmanAuth;\n /** Text appended to the request description. */\n note?: string;\n};\n\n/** The collection-level auth: a bearer token read from the `{{token}}` variable. */\nexport function collectionBearerAuth(): PostmanAuth {\n return { type: \"bearer\", bearer: [{ key: \"token\", value: \"{{token}}\", type: \"string\" }] };\n}\n\nfunction isBearer(scheme: OpenApiSecurityScheme | undefined): boolean {\n return scheme?.type === \"http\" && scheme.scheme.toLowerCase() === \"bearer\";\n}\n\n/**\n * Whether the document declares an HTTP bearer scheme, which is what the collection-level\n * auth stands for.\n */\nexport function hasBearerScheme(components: OpenApiComponents | undefined): boolean {\n return Object.values(components?.securitySchemes ?? {}).some(isBearer);\n}\n\n/**\n * How one operation relates to the collection-level bearer auth.\n *\n * - No `security` (a public route): `noauth`, so the token is not sent.\n * - A bearer requirement: inherits the collection auth.\n * - Cookie-only: `noauth` plus a note, because Postman keeps cookies per domain instead of\n * in collection auth.\n */\nexport function resolveOperationAuth(\n operation: OpenApiOperation,\n components: OpenApiComponents | undefined,\n): OperationAuth {\n const bearerDocument = hasBearerScheme(components);\n const schemes = components?.securitySchemes ?? {};\n const names = (operation.security ?? []).flatMap((requirement) => Object.keys(requirement));\n\n if (names.some((name) => isBearer(schemes[name]))) {\n return {};\n }\n\n const cookies = names.flatMap((name) => {\n const scheme = schemes[name];\n\n return scheme?.type === \"apiKey\" && scheme.in === \"cookie\" ? [scheme.name] : [];\n });\n\n const auth = bearerDocument ? { auth: { type: \"noauth\" } as const } : {};\n\n if (cookies.length === 0) {\n return auth;\n }\n\n const cookieList = cookies.map((cookie) => `\"${cookie}\"`).join(\", \");\n\n return {\n ...auth,\n note: `Authenticates with the ${cookieList} cookie. Postman keeps cookies per domain, so sign in against {{baseUrl}} first or add the cookie in the Cookies manager.`,\n };\n}\n"],"mappings":";;AAWA,SAAgB,uBAAoC;CAClD,OAAO;EAAE,MAAM;EAAU,QAAQ,CAAC;GAAE,KAAK;GAAS,OAAO;GAAa,MAAM;EAAS,CAAC;CAAE;AAC1F;AAEA,SAAS,SAAS,QAAoD;CACpE,OAAO,QAAQ,SAAS,UAAU,OAAO,OAAO,YAAY,MAAM;AACpE;;;;;AAMA,SAAgB,gBAAgB,YAAoD;CAClF,OAAO,OAAO,OAAO,YAAY,mBAAmB,CAAC,CAAC,CAAC,CAAC,KAAK,QAAQ;AACvE;;;;;;;;;AAUA,SAAgB,qBACd,WACA,YACe;CACf,MAAM,iBAAiB,gBAAgB,UAAU;CACjD,MAAM,UAAU,YAAY,mBAAmB,CAAC;CAChD,MAAM,SAAS,UAAU,YAAY,CAAC,EAAC,CAAE,SAAS,gBAAgB,OAAO,KAAK,WAAW,CAAC;CAE1F,IAAI,MAAM,MAAM,SAAS,SAAS,QAAQ,KAAK,CAAC,GAC9C,OAAO,CAAC;CAGV,MAAM,UAAU,MAAM,SAAS,SAAS;EACtC,MAAM,SAAS,QAAQ;EAEvB,OAAO,QAAQ,SAAS,YAAY,OAAO,OAAO,WAAW,CAAC,OAAO,IAAI,IAAI,CAAC;CAChF,CAAC;CAED,MAAM,OAAO,iBAAiB,EAAE,MAAM,EAAE,MAAM,SAAS,EAAW,IAAI,CAAC;CAEvE,IAAI,QAAQ,WAAW,GACrB,OAAO;CAGT,MAAM,aAAa,QAAQ,KAAK,WAAW,IAAI,OAAO,EAAE,CAAC,CAAC,KAAK,IAAI;CAEnE,OAAO;EACL,GAAG;EACH,MAAM,0BAA0B,WAAW;CAC7C;AACF"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schema-refs.d.mts","names":[],"sources":["../../../../../../../../core/src/openapi/postman/schema-refs.ts"],"mappings":";;;KAEY,gBAAA,GAAmB,MAAM,SAAS,aAAA"}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
//#region ../core/src/openapi/postman/schema-refs.ts
|
|
2
|
+
const REF_PREFIX = "#/components/schemas/";
|
|
3
|
+
function isRecord(value) {
|
|
4
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Component name a `$ref` schema points at, or `undefined` for a schema that is not a local
|
|
8
|
+
* component reference.
|
|
9
|
+
*/
|
|
10
|
+
function refName(schema) {
|
|
11
|
+
const ref = schema.$ref;
|
|
12
|
+
return typeof ref === "string" && ref.startsWith(REF_PREFIX) ? ref.slice(21) : void 0;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Follow `$ref`s (with a hop limit, so a ref loop cannot hang) to the schema they name.
|
|
16
|
+
* An unknown component resolves to `{}`.
|
|
17
|
+
*/
|
|
18
|
+
function resolveSchema(schema, components) {
|
|
19
|
+
let current = schema;
|
|
20
|
+
for (let hop = 0; hop < 32; hop++) {
|
|
21
|
+
const name = refName(current);
|
|
22
|
+
if (name === void 0) return current;
|
|
23
|
+
current = components?.[name] ?? {};
|
|
24
|
+
}
|
|
25
|
+
return {};
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* The effective JSON Schema type: `type`, or the first non-null member of a `type` array
|
|
29
|
+
* (the 3.1 nullable form), or one inferred from `properties` / `items`.
|
|
30
|
+
*/
|
|
31
|
+
function primaryType(schema) {
|
|
32
|
+
const { type } = schema;
|
|
33
|
+
if (typeof type === "string") return type;
|
|
34
|
+
if (Array.isArray(type)) return type.find((member) => typeof member === "string" && member !== "null") ?? (type.includes("null") ? "null" : void 0);
|
|
35
|
+
if (isRecord(schema.properties)) return "object";
|
|
36
|
+
if (isRecord(schema.items)) return "array";
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
//#endregion
|
|
40
|
+
export { isRecord, primaryType, refName, resolveSchema };
|
|
41
|
+
//# sourceMappingURL=schema-refs.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schema-refs.mjs","names":[],"sources":["../../../../../../../../core/src/openapi/postman/schema-refs.ts"],"sourcesContent":["import type { OpenApiSchema } from \"../types\";\n\nexport type SchemaComponents = Record<string, OpenApiSchema> | undefined;\n\nconst REF_PREFIX = \"#/components/schemas/\";\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Component name a `$ref` schema points at, or `undefined` for a schema that is not a local\n * component reference.\n */\nexport function refName(schema: OpenApiSchema): string | undefined {\n const ref = schema.$ref;\n\n return typeof ref === \"string\" && ref.startsWith(REF_PREFIX) ? ref.slice(REF_PREFIX.length) : undefined;\n}\n\n/**\n * Follow `$ref`s (with a hop limit, so a ref loop cannot hang) to the schema they name.\n * An unknown component resolves to `{}`.\n */\nexport function resolveSchema(schema: OpenApiSchema, components: SchemaComponents): OpenApiSchema {\n let current = schema;\n\n for (let hop = 0; hop < 32; hop++) {\n const name = refName(current);\n\n if (name === undefined) {\n return current;\n }\n\n current = components?.[name] ?? {};\n }\n\n return {};\n}\n\n/**\n * The effective JSON Schema type: `type`, or the first non-null member of a `type` array\n * (the 3.1 nullable form), or one inferred from `properties` / `items`.\n */\nexport function primaryType(schema: OpenApiSchema): string | undefined {\n const { type } = schema;\n\n if (typeof type === \"string\") {\n return type;\n }\n\n if (Array.isArray(type)) {\n const concrete = type.find((member): member is string => typeof member === \"string\" && member !== \"null\");\n\n return concrete ?? (type.includes(\"null\") ? \"null\" : undefined);\n }\n\n if (isRecord(schema.properties)) {\n return \"object\";\n }\n\n if (isRecord(schema.items)) {\n return \"array\";\n }\n\n return undefined;\n}\n"],"mappings":";AAIA,MAAM,aAAa;AAEnB,SAAgB,SAAS,OAAkD;CACzE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;;;;;AAMA,SAAgB,QAAQ,QAA2C;CACjE,MAAM,MAAM,OAAO;CAEnB,OAAO,OAAO,QAAQ,YAAY,IAAI,WAAW,UAAU,IAAI,IAAI,MAAM,EAAiB,IAAI;AAChG;;;;;AAMA,SAAgB,cAAc,QAAuB,YAA6C;CAChG,IAAI,UAAU;CAEd,KAAK,IAAI,MAAM,GAAG,MAAM,IAAI,OAAO;EACjC,MAAM,OAAO,QAAQ,OAAO;EAE5B,IAAI,SAAS,QACX,OAAO;EAGT,UAAU,aAAa,SAAS,CAAC;CACnC;CAEA,OAAO,CAAC;AACV;;;;;AAMA,SAAgB,YAAY,QAA2C;CACrE,MAAM,EAAE,SAAS;CAEjB,IAAI,OAAO,SAAS,UAClB,OAAO;CAGT,IAAI,MAAM,QAAQ,IAAI,GAGpB,OAFiB,KAAK,MAAM,WAA6B,OAAO,WAAW,YAAY,WAAW,MAEpF,MAAM,KAAK,SAAS,MAAM,IAAI,SAAS;CAGvD,IAAI,SAAS,OAAO,UAAU,GAC5B,OAAO;CAGT,IAAI,SAAS,OAAO,KAAK,GACvB,OAAO;AAIX"}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
|
|
3
|
+
//#region ../core/src/openapi/postman/uuid-v5.ts
|
|
4
|
+
/**
|
|
5
|
+
* Namespace of every id the Postman converter derives. Fixed forever: changing it would
|
|
6
|
+
* change the `_postman_id` of every collection already imported.
|
|
7
|
+
*/
|
|
8
|
+
const POSTMAN_ID_NAMESPACE = "8f1c2b64-3d7a-4c59-9a0e-5b6d1e47c2a3";
|
|
9
|
+
/**
|
|
10
|
+
* RFC 4122 version 5 (SHA-1, name based) UUID, so the same name always yields the same id.
|
|
11
|
+
*/
|
|
12
|
+
function uuidV5(name, namespace = POSTMAN_ID_NAMESPACE) {
|
|
13
|
+
const digest = createHash("sha1").update(Buffer.from(namespace.replace(/-/g, ""), "hex")).update(name, "utf8").digest();
|
|
14
|
+
const bytes = Buffer.from(digest.subarray(0, 16));
|
|
15
|
+
bytes.writeUInt8(bytes.readUInt8(6) & 15 | 80, 6);
|
|
16
|
+
bytes.writeUInt8(bytes.readUInt8(8) & 63 | 128, 8);
|
|
17
|
+
const hex = bytes.toString("hex");
|
|
18
|
+
return [
|
|
19
|
+
hex.slice(0, 8),
|
|
20
|
+
hex.slice(8, 12),
|
|
21
|
+
hex.slice(12, 16),
|
|
22
|
+
hex.slice(16, 20),
|
|
23
|
+
hex.slice(20, 32)
|
|
24
|
+
].join("-");
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
//#endregion
|
|
28
|
+
export { uuidV5 };
|
|
29
|
+
//# sourceMappingURL=uuid-v5.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"uuid-v5.mjs","names":[],"sources":["../../../../../../../../core/src/openapi/postman/uuid-v5.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\n\n/**\n * Namespace of every id the Postman converter derives. Fixed forever: changing it would\n * change the `_postman_id` of every collection already imported.\n */\nexport const POSTMAN_ID_NAMESPACE = \"8f1c2b64-3d7a-4c59-9a0e-5b6d1e47c2a3\";\n\n/**\n * RFC 4122 version 5 (SHA-1, name based) UUID, so the same name always yields the same id.\n */\nexport function uuidV5(name: string, namespace: string = POSTMAN_ID_NAMESPACE): string {\n const digest = createHash(\"sha1\")\n .update(Buffer.from(namespace.replace(/-/g, \"\"), \"hex\"))\n .update(name, \"utf8\")\n .digest();\n const bytes = Buffer.from(digest.subarray(0, 16));\n\n bytes.writeUInt8((bytes.readUInt8(6) & 0x0f) | 0x50, 6);\n bytes.writeUInt8((bytes.readUInt8(8) & 0x3f) | 0x80, 8);\n\n const hex = bytes.toString(\"hex\");\n\n return [hex.slice(0, 8), hex.slice(8, 12), hex.slice(12, 16), hex.slice(16, 20), hex.slice(20, 32)].join(\"-\");\n}\n"],"mappings":";;;;;;;AAMA,MAAa,uBAAuB;;;;AAKpC,SAAgB,OAAO,MAAc,YAAoB,sBAA8B;CACrF,MAAM,SAAS,WAAW,MAAM,CAAC,CAC9B,OAAO,OAAO,KAAK,UAAU,QAAQ,MAAM,EAAE,GAAG,KAAK,CAAC,CAAC,CACvD,OAAO,MAAM,MAAM,CAAC,CACpB,OAAO;CACV,MAAM,QAAQ,OAAO,KAAK,OAAO,SAAS,GAAG,EAAE,CAAC;CAEhD,MAAM,WAAY,MAAM,UAAU,CAAC,IAAI,KAAQ,IAAM,CAAC;CACtD,MAAM,WAAY,MAAM,UAAU,CAAC,IAAI,KAAQ,KAAM,CAAC;CAEtD,MAAM,MAAM,MAAM,SAAS,KAAK;CAEhC,OAAO;EAAC,IAAI,MAAM,GAAG,CAAC;EAA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ference(value, outputSettings === "self[]");
|
|
106
106
|
else if (typeof outputSettings === "function" && outputSettings.prototype instanceof Resource) {
|
|
107
107
|
if (!value) return;
|
|
108
|
-
if (Array.isArray(value))
|
|
109
|
-
|
|
110
|
-
outputValue = value.map((item) => new outputSettings(item).toJSON()).filter((v) => v !== void 0);
|
|
111
|
-
} else outputValue = new outputSettings(value).toJSON();
|
|
108
|
+
if (Array.isArray(value)) outputValue = value.map((item) => new outputSettings(item).toJSON()).filter((v) => v !== void 0);
|
|
109
|
+
else outputValue = new outputSettings(value).toJSON();
|
|
112
110
|
} else if (typeof outputSettings === "function") outputValue = outputSettings.call(this, value, this);
|
|
113
111
|
else if (outputSettings instanceof ResourceFieldBuilder) outputValue = outputSettings.transform(value, locale);
|
|
114
112
|
else if (typeof outputSettings === "object" && outputSettings !== null && "__type" in outputSettings && outputSettings.__type === "arrayOf") if (Array.isArray(value)) outputValue = value.map((item) => this.transformArrayItem(item, outputSettings.schema, locale)).filter((v) => v !== void 0);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resource.mjs","names":[],"sources":["../../../../../../../core/src/resource/resource.ts"],"sourcesContent":["import { get, isLazy, set, type GenericObject } from \"@mongez/reinforcements\";\nimport { Model } from \"@warlock.js/cascade\";\nimport { useRequestStore } from \"../http/context/request-context\";\nimport { ResourceFieldBuilder } from \"./resource-field-builder\";\nimport {\n type ResourceArraySchema,\n type ResourceFieldConfig,\n type ResourceOutputValueCastType,\n type ResourceSchema,\n} from \"./types\";\n\n/**\n * Maximum recursion depth for self-referencing fields.\n * Prevents runaway serialization on deep trees or circular data.\n */\nconst MAX_SELF_DEPTH = 10;\n\n/**\n * Resource contract\n */\nexport interface ResourceContract<Out = GenericObject> {\n /**\n * Resource data\n */\n resource: GenericObject;\n\n /**\n * Resource final output\n */\n data: GenericObject;\n\n /**\n * Original data\n */\n originalData: GenericObject;\n\n /**\n * Convert resource to JSON\n */\n toJSON(): Out;\n\n /**\n * Transform the given value with given type\n */\n transform(value: any, type: ResourceOutputValueCastType, locale?: string): any;\n\n /**\n * Get a input value for the given key\n */\n get(key: string, defaultValue?: any): any;\n\n /**\n * Set the given value for the given field\n */\n set(key: string, value: any): ResourceContract;\n\n /**\n * Create an array schema for transforming array items\n */\n arrayOf(schema: Record<string, ResourceFieldConfig>): ResourceArraySchema;\n\n /**\n * Get a string field builder\n */\n string(inputKey?: string): ResourceFieldBuilder;\n\n /**\n * Get a date field builder\n */\n date(inputKey?: string): ResourceFieldBuilder;\n\n /**\n * Get a localized field builder\n */\n localized(inputKey?: string): ResourceFieldBuilder;\n\n /**\n * Get a url field builder\n */\n url(inputKey?: string): ResourceFieldBuilder;\n\n /**\n * Get a uploadsUrl field builder\n */\n uploadsUrl(inputKey?: string): ResourceFieldBuilder;\n\n /**\n * Get a number field builder\n */\n number(inputKey?: string): ResourceFieldBuilder;\n\n /**\n * Get a boolean field builder\n */\n boolean(inputKey?: string): ResourceFieldBuilder;\n\n /**\n * Get a float field builder\n */\n float(inputKey?: string): ResourceFieldBuilder;\n\n /**\n * Get a int field builder\n */\n int(inputKey?: string): ResourceFieldBuilder;\n}\n\n/**\n * Resource constructor\n */\nexport interface ResourceConstructor<Out = GenericObject> {\n new (originalData: GenericObject | Resource | Model): ResourceContract<Out>;\n}\n\nexport class Resource implements ResourceContract {\n /**\n * Resource data\n */\n public resource: GenericObject = {};\n\n /**\n * Resource final output\n */\n public data: GenericObject = {};\n\n /**\n * Tracks visited object identities during self-reference recursion.\n * Prevents infinite loops on circular data (e.g. A.parent → B, B.parent → A).\n */\n protected _selfSeen?: Set<unknown>;\n\n /**\n * Raw resource schema — field declarations as written by the developer.\n * Used by doc generators for introspection.\n */\n public static schema: Record<string, ResourceFieldConfig | string> = {};\n\n /**\n * Normalized schema — all string cast types and tuples converted to\n * ResourceFieldBuilder instances at definition time. Used by transformOutput at runtime.\n */\n public static parsedSchema: Record<string, ResourceFieldConfig> = {};\n\n /**\n * Normalize a raw schema into parsedSchema.\n * Converts string cast types (including suffixes) and tuples into pre-built builders.\n * Other entry types (ResourceConstructor, resolver functions, ResourceArraySchema) are kept as-is.\n */\n public static normalizeSchema(schema: Record<string, ResourceFieldConfig | string>): Record<string, ResourceFieldConfig> {\n const parsed: Record<string, ResourceFieldConfig> = {};\n\n for (const [key, value] of Object.entries(schema)) {\n if (value === \"self\" || value === \"self[]\") {\n // Keep self-references as-is — resolved lazily in transformValue\n parsed[key] = value;\n } else if (isLazy<ResourceConstructor>(value)) {\n // Keep Lazy<ResourceConstructor> as-is — resolved at transform\n // time so cyclic resource refs (A embeds B embeds A) compose\n // without import-graph cycles.\n parsed[key] = value;\n } else if (typeof value === \"string\") {\n parsed[key] = ResourceFieldBuilder.fromCastType(value);\n } else if (Array.isArray(value) && value.length === 2 && typeof value[0] === \"string\") {\n const builder = ResourceFieldBuilder.fromCastType(value[1] as string);\n builder.setInputKey(value[0]);\n parsed[key] = builder;\n } else {\n parsed[key] = value;\n }\n }\n\n return parsed;\n }\n\n /**\n * Constructor\n */\n public constructor(public originalData: GenericObject | Resource | Model) {\n if (this.originalData instanceof Model) {\n this.resource = this.originalData.data;\n } else if (this.originalData instanceof Resource) {\n this.resource = this.originalData.data;\n } else {\n this.resource = this.originalData;\n }\n }\n\n /**\n * Convert resource to JSON\n */\n public toJSON() {\n this.boot();\n this.transformOutput();\n this.extend();\n\n return this.data;\n }\n\n /**\n * Boot method\n * Called before transforming the resource\n */\n protected boot() {\n //\n }\n\n /**\n * Transform resource to output using the pre-normalized parsedSchema.\n * Builders handle their own array/nullable logic internally.\n * ResourceConstructor and ResourceArraySchema handle arrays in transformValue.\n */\n protected transformOutput() {\n const localeCode = useRequestStore()?.request?.locale;\n const parsedSchema = this.resolveParsedSchema();\n // A model is read through its accessors; anything else through the\n // constructor's normalized input (a wrapped resource's serialized data).\n const source = this.originalData instanceof Model ? this.originalData : this.resource;\n\n for (const [outputKey, outputSettings] of Object.entries(parsedSchema)) {\n const inputKey = outputSettings instanceof ResourceFieldBuilder\n ? outputSettings.getInputKey()\n : undefined;\n const inputValue = this.resolveSourceValue(source, outputKey, inputKey);\n const outputValue = this.transformValue(inputValue, outputSettings, localeCode);\n\n if (outputValue !== undefined) {\n this.set(outputKey, outputValue);\n }\n }\n }\n\n /**\n * Resolve the normalized schema of THIS class.\n * `@RegisterResource()` is optional: when the class has no own `parsedSchema`\n * (a static field is inherited from the base as `{}`), normalize its own\n * static `schema` (or an instance `schema` field) once and cache it on the class.\n */\n protected resolveParsedSchema(): Record<string, ResourceFieldConfig> {\n const ctor = this.constructor as typeof Resource;\n\n if (Object.hasOwn(ctor, \"parsedSchema\")) {\n return ctor.parsedSchema;\n }\n\n const instanceSchema = (this as unknown as { schema?: Record<string, ResourceFieldConfig | string> }).schema;\n const schema = instanceSchema ?? ctor.schema;\n\n if (!schema || Object.keys(schema).length === 0) {\n throw new Error(\n `Resource \"${ctor.name}\" has no schema. Declare \\`static schema = { ... }\\` on the class.`,\n );\n }\n\n const parsed = Resource.normalizeSchema(schema);\n\n // Instance schemas are per-class by convention, so caching on the class is safe\n ctor.parsedSchema = parsed;\n\n return parsed;\n }\n\n /**\n * Transform the given value with given type\n */\n public transform(value: any, type: ResourceOutputValueCastType, locale?: string) {\n return new ResourceFieldBuilder(type).transform(value, locale);\n }\n\n /**\n * Transform the given value for the given output setting.\n * After normalization, string cast types no longer reach here — they are pre-converted to builders.\n */\n protected transformValue(value: any, outputSettings: ResourceFieldConfig, locale?: string): any {\n let outputValue: any;\n\n if (isLazy<ResourceConstructor>(outputSettings)) {\n // Resolve the lazy ref now (cyclic resource imports are fully loaded\n // by serialization time) and recurse — the resolved constructor is\n // handled by the ResourceConstructor branch below.\n return this.transformValue(value, outputSettings.resolve(), locale);\n }\n\n if (outputSettings === \"self\" || outputSettings === \"self[]\") {\n // Self-reference — resolve using the same resource class with cycle detection\n outputValue = this.transformSelfReference(value, outputSettings === \"self[]\");\n } else if (\n typeof outputSettings === \"function\" &&\n outputSettings.prototype instanceof Resource\n ) {\n if (!value) return;\n // Nested resource — handle both single and array values\n if (Array.isArray(value)) {\n if (value.length === 0) return;\n outputValue = value\n .map((item) => new (outputSettings as typeof Resource)(item).toJSON())\n .filter((v) => v !== undefined);\n } else {\n outputValue = new (outputSettings as typeof Resource)(value).toJSON();\n }\n } else if (typeof outputSettings === \"function\") {\n // Resolver function - bind to Resource instance for access to this.get(), etc.\n outputValue = (outputSettings as Function).call(this, value, this);\n } else if (outputSettings instanceof ResourceFieldBuilder) {\n // Builder — handles array mapping and nullable internally via isArrayField\n outputValue = outputSettings.transform(value, locale);\n } else if (\n typeof outputSettings === \"object\" &&\n outputSettings !== null &&\n \"__type\" in outputSettings &&\n outputSettings.__type === \"arrayOf\"\n ) {\n // ResourceArraySchema — structured array items with their own sub-schema\n if (Array.isArray(value)) {\n outputValue = value\n .map((item) => this.transformArrayItem(item, outputSettings.schema, locale))\n .filter((v) => v !== undefined);\n } else {\n outputValue = this.transformArrayItem(value, outputSettings.schema, locale);\n }\n }\n\n return outputValue;\n }\n\n /**\n * Extend the resource output\n */\n protected extend() {\n //\n }\n\n /**\n * Transform a self-referencing field value.\n *\n * @example\n * // Single: parent: \"self\"\n * // Array: children: \"self[]\"\n */\n protected transformSelfReference(value: any, isArray: boolean): any {\n if (isArray) {\n return Array.isArray(value)\n ? value.map((item) => this.resolveSelf(item)).filter((v) => v !== undefined)\n : undefined;\n }\n\n return this.resolveSelf(value);\n }\n\n /**\n * Resolve a single self-reference value.\n * Uses identity-based cycle detection (id/_id) and a max depth guard.\n */\n protected resolveSelf(value: any): any {\n if (!value) return undefined;\n\n const identity = value.id ?? value._id ?? value;\n // Ancestors of the current path only: siblings never see each other,\n // so the set size is the depth.\n const ancestors = this._selfSeen ?? new Set();\n\n // Circular reference or depth limit reached — stop recursion\n if (ancestors.has(identity) || ancestors.size >= MAX_SELF_DEPTH) {\n return undefined;\n }\n\n const SelfConstructor = this.constructor as typeof Resource;\n const child = new SelfConstructor(value);\n child._selfSeen = new Set(ancestors).add(identity);\n\n return child.toJSON();\n }\n\n /**\n * Transform a single array item according to the given schema\n */\n protected transformArrayItem(\n item: any,\n schema: Record<string, ResourceFieldConfig>,\n locale?: string,\n ) {\n const transformedItem: GenericObject = {};\n\n for (const [outputKey, outputSettings] of Object.entries(schema)) {\n let fieldKey = outputKey;\n let valueTransformType = outputSettings as ResourceFieldConfig;\n\n if (Array.isArray(outputSettings)) {\n fieldKey = outputSettings[0];\n valueTransformType = outputSettings[1];\n }\n\n const inputKey = valueTransformType instanceof ResourceFieldBuilder\n ? valueTransformType.getInputKey()\n : undefined;\n const inputValue = this.resolveSourceValue(item, outputKey, inputKey ?? fieldKey);\n const outputValue = this.transformValue(inputValue, valueTransformType, locale);\n\n if (outputValue !== undefined) {\n set(transformedItem, outputKey, outputValue);\n }\n }\n\n return transformedItem;\n }\n\n /**\n * Resolve one schema field from a model or plain object. Mongo records use `_id`\n * internally, while resources expose `id` by convention.\n */\n protected resolveSourceValue(source: GenericObject | Resource | Model, outputKey: string, inputKey?: string) {\n const key = inputKey ?? outputKey;\n const read = (field: string) => source instanceof Model ? source.get(field) : get(source, field);\n const value = read(key);\n\n return outputKey === \"id\" && key === \"id\" && value === undefined ? read(\"_id\") : value;\n }\n\n /**\n * Get a input value for the given key\n */\n public get(key: string, defaultValue?: any) {\n return get(this.resource, key, defaultValue);\n }\n\n /**\n * Set the given value for the given field\n */\n public set(key: string, value: any): ResourceContract {\n set(this.data, key, value);\n\n return this;\n }\n\n /**\n * Create an array schema for transforming array items\n */\n public arrayOf(schema: Record<string, ResourceFieldConfig>): ResourceArraySchema {\n return {\n __type: \"arrayOf\",\n schema,\n };\n }\n\n /**\n * Get a string field builder\n */\n public string(inputKey?: string) {\n return this.fieldBuilder(\"string\", inputKey);\n }\n\n /**\n * Get a date field builder\n */\n public date(inputKey?: string) {\n return this.fieldBuilder(\"date\", inputKey);\n }\n\n /**\n * Get a localized field builder\n */\n public localized(inputKey?: string) {\n return this.fieldBuilder(\"localized\", inputKey);\n }\n\n /**\n * Get a url field builder\n */\n public url(inputKey?: string) {\n return this.fieldBuilder(\"url\", inputKey);\n }\n\n /**\n * Get a uploadsUrl field builder\n */\n public uploadsUrl(inputKey?: string) {\n return this.fieldBuilder(\"uploadsUrl\", inputKey);\n }\n\n /**\n * Get a number field builder\n */\n public number(inputKey?: string) {\n return this.fieldBuilder(\"number\", inputKey);\n }\n\n /**\n * Get a boolean field builder\n */\n public boolean(inputKey?: string) {\n return this.fieldBuilder(\"boolean\", inputKey);\n }\n\n /**\n * Get a float field builder\n */\n public float(inputKey?: string) {\n return this.fieldBuilder(\"float\", inputKey);\n }\n\n /**\n * Get a int field builder\n */\n public int(inputKey?: string) {\n return this.fieldBuilder(\"int\", inputKey);\n }\n\n /**\n * New field builder\n */\n protected fieldBuilder(type: ResourceOutputValueCastType, inputKey?: string) {\n const builder = new ResourceFieldBuilder(type);\n\n if (inputKey) {\n builder.setInputKey(inputKey);\n }\n\n return builder;\n }\n}\n"],"mappings":";;;;;;;;;;AAeA,MAAM,iBAAiB;AAmGvB,IAAa,WAAb,MAAa,SAAqC;;gBAqBqB,CAAC;;;sBAMJ,CAAC;;;;;;;CAOnE,OAAc,gBAAgB,QAA2F;EACvH,MAAM,SAA8C,CAAC;EAErD,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,MAAM,GAC9C,IAAI,UAAU,UAAU,UAAU,UAEhC,OAAO,OAAO;OACT,IAAI,OAA4B,KAAK,GAI1C,OAAO,OAAO;OACT,IAAI,OAAO,UAAU,UAC1B,OAAO,OAAO,qBAAqB,aAAa,KAAK;OAChD,IAAI,MAAM,QAAQ,KAAK,KAAK,MAAM,WAAW,KAAK,OAAO,MAAM,OAAO,UAAU;GACrF,MAAM,UAAU,qBAAqB,aAAa,MAAM,EAAY;GACpE,QAAQ,YAAY,MAAM,EAAE;GAC5B,OAAO,OAAO;EAChB,OACE,OAAO,OAAO;EAIlB,OAAO;CACT;;;;CAKA,AAAO,YAAY,AAAO,cAAgD;EAAhD;k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;;;CAKA,AAAO,QAAQ,QAAkE;EAC/E,OAAO;GACL,QAAQ;GACR;EACF;CACF;;;;CAKA,AAAO,OAAO,UAAmB;EAC/B,OAAO,KAAK,aAAa,UAAU,QAAQ;CAC7C;;;;CAKA,AAAO,KAAK,UAAmB;EAC7B,OAAO,KAAK,aAAa,QAAQ,QAAQ;CAC3C;;;;CAKA,AAAO,UAAU,UAAmB;EAClC,OAAO,KAAK,aAAa,aAAa,QAAQ;CAChD;;;;CAKA,AAAO,IAAI,UAAmB;EAC5B,OAAO,KAAK,aAAa,OAAO,QAAQ;CAC1C;;;;CAKA,AAAO,WAAW,UAAmB;EACnC,OAAO,KAAK,aAAa,cAAc,QAAQ;CACjD;;;;CAKA,AAAO,OAAO,UAAmB;EAC/B,OAAO,KAAK,aAAa,UAAU,QAAQ;CAC7C;;;;CAKA,AAAO,QAAQ,UAAmB;EAChC,OAAO,KAAK,aAAa,WAAW,QAAQ;CAC9C;;;;CAKA,AAAO,MAAM,UAAmB;EAC9B,OAAO,KAAK,aAAa,SAAS,QAAQ;CAC5C;;;;CAKA,AAAO,IAAI,UAAmB;EAC5B,OAAO,KAAK,aAAa,OAAO,QAAQ;CAC1C;;;;CAKA,AAAU,aAAa,MAAmC,UAAmB;EAC3E,MAAM,UAAU,IAAI,qBAAqB,IAAI;EAE7C,IAAI,UACF,QAAQ,YAAY,QAAQ;EAG9B,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"resource.mjs","names":[],"sources":["../../../../../../../core/src/resource/resource.ts"],"sourcesContent":["import { get, isLazy, set, type GenericObject } from \"@mongez/reinforcements\";\nimport { Model } from \"@warlock.js/cascade\";\nimport { useRequestStore } from \"../http/context/request-context\";\nimport { ResourceFieldBuilder } from \"./resource-field-builder\";\nimport {\n type ResourceArraySchema,\n type ResourceFieldConfig,\n type ResourceOutputValueCastType,\n type ResourceSchema,\n} from \"./types\";\n\n/**\n * Maximum recursion depth for self-referencing fields.\n * Prevents runaway serialization on deep trees or circular data.\n */\nconst MAX_SELF_DEPTH = 10;\n\n/**\n * Resource contract\n */\nexport interface ResourceContract<Out = GenericObject> {\n /**\n * Resource data\n */\n resource: GenericObject;\n\n /**\n * Resource final output\n */\n data: GenericObject;\n\n /**\n * Original data\n */\n originalData: GenericObject;\n\n /**\n * Convert resource to JSON\n */\n toJSON(): Out;\n\n /**\n * Transform the given value with given type\n */\n transform(value: any, type: ResourceOutputValueCastType, locale?: string): any;\n\n /**\n * Get a input value for the given key\n */\n get(key: string, defaultValue?: any): any;\n\n /**\n * Set the given value for the given field\n */\n set(key: string, value: any): ResourceContract;\n\n /**\n * Create an array schema for transforming array items\n */\n arrayOf(schema: Record<string, ResourceFieldConfig>): ResourceArraySchema;\n\n /**\n * Get a string field builder\n */\n string(inputKey?: string): ResourceFieldBuilder;\n\n /**\n * Get a date field builder\n */\n date(inputKey?: string): ResourceFieldBuilder;\n\n /**\n * Get a localized field builder\n */\n localized(inputKey?: string): ResourceFieldBuilder;\n\n /**\n * Get a url field builder\n */\n url(inputKey?: string): ResourceFieldBuilder;\n\n /**\n * Get a uploadsUrl field builder\n */\n uploadsUrl(inputKey?: string): ResourceFieldBuilder;\n\n /**\n * Get a number field builder\n */\n number(inputKey?: string): ResourceFieldBuilder;\n\n /**\n * Get a boolean field builder\n */\n boolean(inputKey?: string): ResourceFieldBuilder;\n\n /**\n * Get a float field builder\n */\n float(inputKey?: string): ResourceFieldBuilder;\n\n /**\n * Get a int field builder\n */\n int(inputKey?: string): ResourceFieldBuilder;\n}\n\n/**\n * Resource constructor\n */\nexport interface ResourceConstructor<Out = GenericObject> {\n new (originalData: GenericObject | Resource | Model): ResourceContract<Out>;\n}\n\nexport class Resource implements ResourceContract {\n /**\n * Resource data\n */\n public resource: GenericObject = {};\n\n /**\n * Resource final output\n */\n public data: GenericObject = {};\n\n /**\n * Tracks visited object identities during self-reference recursion.\n * Prevents infinite loops on circular data (e.g. A.parent → B, B.parent → A).\n */\n protected _selfSeen?: Set<unknown>;\n\n /**\n * Raw resource schema — field declarations as written by the developer.\n * Used by doc generators for introspection.\n */\n public static schema: Record<string, ResourceFieldConfig | string> = {};\n\n /**\n * Normalized schema — all string cast types and tuples converted to\n * ResourceFieldBuilder instances at definition time. Used by transformOutput at runtime.\n */\n public static parsedSchema: Record<string, ResourceFieldConfig> = {};\n\n /**\n * Normalize a raw schema into parsedSchema.\n * Converts string cast types (including suffixes) and tuples into pre-built builders.\n * Other entry types (ResourceConstructor, resolver functions, ResourceArraySchema) are kept as-is.\n */\n public static normalizeSchema(schema: Record<string, ResourceFieldConfig | string>): Record<string, ResourceFieldConfig> {\n const parsed: Record<string, ResourceFieldConfig> = {};\n\n for (const [key, value] of Object.entries(schema)) {\n if (value === \"self\" || value === \"self[]\") {\n // Keep self-references as-is — resolved lazily in transformValue\n parsed[key] = value;\n } else if (isLazy<ResourceConstructor>(value)) {\n // Keep Lazy<ResourceConstructor> as-is — resolved at transform\n // time so cyclic resource refs (A embeds B embeds A) compose\n // without import-graph cycles.\n parsed[key] = value;\n } else if (typeof value === \"string\") {\n parsed[key] = ResourceFieldBuilder.fromCastType(value);\n } else if (Array.isArray(value) && value.length === 2 && typeof value[0] === \"string\") {\n const builder = ResourceFieldBuilder.fromCastType(value[1] as string);\n builder.setInputKey(value[0]);\n parsed[key] = builder;\n } else {\n parsed[key] = value;\n }\n }\n\n return parsed;\n }\n\n /**\n * Constructor\n */\n public constructor(public originalData: GenericObject | Resource | Model) {\n if (this.originalData instanceof Model) {\n this.resource = this.originalData.data;\n } else if (this.originalData instanceof Resource) {\n this.resource = this.originalData.data;\n } else {\n this.resource = this.originalData;\n }\n }\n\n /**\n * Convert resource to JSON\n */\n public toJSON() {\n this.boot();\n this.transformOutput();\n this.extend();\n\n return this.data;\n }\n\n /**\n * Boot method\n * Called before transforming the resource\n */\n protected boot() {\n //\n }\n\n /**\n * Transform resource to output using the pre-normalized parsedSchema.\n * Builders handle their own array/nullable logic internally.\n * ResourceConstructor and ResourceArraySchema handle arrays in transformValue.\n */\n protected transformOutput() {\n const localeCode = useRequestStore()?.request?.locale;\n const parsedSchema = this.resolveParsedSchema();\n // A model is read through its accessors; anything else through the\n // constructor's normalized input (a wrapped resource's serialized data).\n const source = this.originalData instanceof Model ? this.originalData : this.resource;\n\n for (const [outputKey, outputSettings] of Object.entries(parsedSchema)) {\n const inputKey = outputSettings instanceof ResourceFieldBuilder\n ? outputSettings.getInputKey()\n : undefined;\n const inputValue = this.resolveSourceValue(source, outputKey, inputKey);\n const outputValue = this.transformValue(inputValue, outputSettings, localeCode);\n\n if (outputValue !== undefined) {\n this.set(outputKey, outputValue);\n }\n }\n }\n\n /**\n * Resolve the normalized schema of THIS class.\n * `@RegisterResource()` is optional: when the class has no own `parsedSchema`\n * (a static field is inherited from the base as `{}`), normalize its own\n * static `schema` (or an instance `schema` field) once and cache it on the class.\n */\n protected resolveParsedSchema(): Record<string, ResourceFieldConfig> {\n const ctor = this.constructor as typeof Resource;\n\n if (Object.hasOwn(ctor, \"parsedSchema\")) {\n return ctor.parsedSchema;\n }\n\n const instanceSchema = (this as unknown as { schema?: Record<string, ResourceFieldConfig | string> }).schema;\n const schema = instanceSchema ?? ctor.schema;\n\n if (!schema || Object.keys(schema).length === 0) {\n throw new Error(\n `Resource \"${ctor.name}\" has no schema. Declare \\`static schema = { ... }\\` on the class.`,\n );\n }\n\n const parsed = Resource.normalizeSchema(schema);\n\n // Instance schemas are per-class by convention, so caching on the class is safe\n ctor.parsedSchema = parsed;\n\n return parsed;\n }\n\n /**\n * Transform the given value with given type\n */\n public transform(value: any, type: ResourceOutputValueCastType, locale?: string) {\n return new ResourceFieldBuilder(type).transform(value, locale);\n }\n\n /**\n * Transform the given value for the given output setting.\n * After normalization, string cast types no longer reach here — they are pre-converted to builders.\n */\n protected transformValue(value: any, outputSettings: ResourceFieldConfig, locale?: string): any {\n let outputValue: any;\n\n if (isLazy<ResourceConstructor>(outputSettings)) {\n // Resolve the lazy ref now (cyclic resource imports are fully loaded\n // by serialization time) and recurse — the resolved constructor is\n // handled by the ResourceConstructor branch below.\n return this.transformValue(value, outputSettings.resolve(), locale);\n }\n\n if (outputSettings === \"self\" || outputSettings === \"self[]\") {\n // Self-reference — resolve using the same resource class with cycle detection\n outputValue = this.transformSelfReference(value, outputSettings === \"self[]\");\n } else if (\n typeof outputSettings === \"function\" &&\n outputSettings.prototype instanceof Resource\n ) {\n if (!value) return;\n // Nested resource — handle both single and array values\n if (Array.isArray(value)) {\n // An empty list stays an empty list ([] is the honest output); only a\n // missing/null input omits the field.\n outputValue = value\n .map((item) => new (outputSettings as typeof Resource)(item).toJSON())\n .filter((v) => v !== undefined);\n } else {\n outputValue = new (outputSettings as typeof Resource)(value).toJSON();\n }\n } else if (typeof outputSettings === \"function\") {\n // Resolver function - bind to Resource instance for access to this.get(), etc.\n outputValue = (outputSettings as Function).call(this, value, this);\n } else if (outputSettings instanceof ResourceFieldBuilder) {\n // Builder — handles array mapping and nullable internally via isArrayField\n outputValue = outputSettings.transform(value, locale);\n } else if (\n typeof outputSettings === \"object\" &&\n outputSettings !== null &&\n \"__type\" in outputSettings &&\n outputSettings.__type === \"arrayOf\"\n ) {\n // ResourceArraySchema — structured array items with their own sub-schema\n if (Array.isArray(value)) {\n outputValue = value\n .map((item) => this.transformArrayItem(item, outputSettings.schema, locale))\n .filter((v) => v !== undefined);\n } else {\n outputValue = this.transformArrayItem(value, outputSettings.schema, locale);\n }\n }\n\n return outputValue;\n }\n\n /**\n * Extend the resource output\n */\n protected extend() {\n //\n }\n\n /**\n * Transform a self-referencing field value.\n *\n * @example\n * // Single: parent: \"self\"\n * // Array: children: \"self[]\"\n */\n protected transformSelfReference(value: any, isArray: boolean): any {\n if (isArray) {\n return Array.isArray(value)\n ? value.map((item) => this.resolveSelf(item)).filter((v) => v !== undefined)\n : undefined;\n }\n\n return this.resolveSelf(value);\n }\n\n /**\n * Resolve a single self-reference value.\n * Uses identity-based cycle detection (id/_id) and a max depth guard.\n */\n protected resolveSelf(value: any): any {\n if (!value) return undefined;\n\n const identity = value.id ?? value._id ?? value;\n // Ancestors of the current path only: siblings never see each other,\n // so the set size is the depth.\n const ancestors = this._selfSeen ?? new Set();\n\n // Circular reference or depth limit reached — stop recursion\n if (ancestors.has(identity) || ancestors.size >= MAX_SELF_DEPTH) {\n return undefined;\n }\n\n const SelfConstructor = this.constructor as typeof Resource;\n const child = new SelfConstructor(value);\n child._selfSeen = new Set(ancestors).add(identity);\n\n return child.toJSON();\n }\n\n /**\n * Transform a single array item according to the given schema\n */\n protected transformArrayItem(\n item: any,\n schema: Record<string, ResourceFieldConfig>,\n locale?: string,\n ) {\n const transformedItem: GenericObject = {};\n\n for (const [outputKey, outputSettings] of Object.entries(schema)) {\n let fieldKey = outputKey;\n let valueTransformType = outputSettings as ResourceFieldConfig;\n\n if (Array.isArray(outputSettings)) {\n fieldKey = outputSettings[0];\n valueTransformType = outputSettings[1];\n }\n\n const inputKey = valueTransformType instanceof ResourceFieldBuilder\n ? valueTransformType.getInputKey()\n : undefined;\n const inputValue = this.resolveSourceValue(item, outputKey, inputKey ?? fieldKey);\n const outputValue = this.transformValue(inputValue, valueTransformType, locale);\n\n if (outputValue !== undefined) {\n set(transformedItem, outputKey, outputValue);\n }\n }\n\n return transformedItem;\n }\n\n /**\n * Resolve one schema field from a model or plain object. Mongo records use `_id`\n * internally, while resources expose `id` by convention.\n */\n protected resolveSourceValue(source: GenericObject | Resource | Model, outputKey: string, inputKey?: string) {\n const key = inputKey ?? outputKey;\n const read = (field: string) => source instanceof Model ? source.get(field) : get(source, field);\n const value = read(key);\n\n return outputKey === \"id\" && key === \"id\" && value === undefined ? read(\"_id\") : value;\n }\n\n /**\n * Get a input value for the given key\n */\n public get(key: string, defaultValue?: any) {\n return get(this.resource, key, defaultValue);\n }\n\n /**\n * Set the given value for the given field\n */\n public set(key: string, value: any): ResourceContract {\n set(this.data, key, value);\n\n return this;\n }\n\n /**\n * Create an array schema for transforming array items\n */\n public arrayOf(schema: Record<string, ResourceFieldConfig>): ResourceArraySchema {\n return {\n __type: \"arrayOf\",\n schema,\n };\n }\n\n /**\n * Get a string field builder\n */\n public string(inputKey?: string) {\n return this.fieldBuilder(\"string\", inputKey);\n }\n\n /**\n * Get a date field builder\n */\n public date(inputKey?: string) {\n return this.fieldBuilder(\"date\", inputKey);\n }\n\n /**\n * Get a localized field builder\n */\n public localized(inputKey?: string) {\n return this.fieldBuilder(\"localized\", inputKey);\n }\n\n /**\n * Get a url field builder\n */\n public url(inputKey?: string) {\n return this.fieldBuilder(\"url\", inputKey);\n }\n\n /**\n * Get a uploadsUrl field builder\n */\n public uploadsUrl(inputKey?: string) {\n return this.fieldBuilder(\"uploadsUrl\", inputKey);\n }\n\n /**\n * Get a number field builder\n */\n public number(inputKey?: string) {\n return this.fieldBuilder(\"number\", inputKey);\n }\n\n /**\n * Get a boolean field builder\n */\n public boolean(inputKey?: string) {\n return this.fieldBuilder(\"boolean\", inputKey);\n }\n\n /**\n * Get a float field builder\n */\n public float(inputKey?: string) {\n return this.fieldBuilder(\"float\", inputKey);\n }\n\n /**\n * Get a int field builder\n */\n public int(inputKey?: string) {\n return this.fieldBuilder(\"int\", inputKey);\n }\n\n /**\n * New field builder\n */\n protected fieldBuilder(type: ResourceOutputValueCastType, inputKey?: string) {\n const builder = new ResourceFieldBuilder(type);\n\n if (inputKey) {\n builder.setInputKey(inputKey);\n }\n\n return builder;\n }\n}\n"],"mappings":";;;;;;;;;;AAeA,MAAM,iBAAiB;AAmGvB,IAAa,WAAb,MAAa,SAAqC;;gBAqBqB,CAAC;;;sBAMJ,CAAC;;;;;;;CAOnE,OAAc,gBAAgB,QAA2F;EACvH,MAAM,SAA8C,CAAC;EAErD,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,MAAM,GAC9C,IAAI,UAAU,UAAU,UAAU,UAEhC,OAAO,OAAO;OACT,IAAI,OAA4B,KAAK,GAI1C,OAAO,OAAO;OACT,IAAI,OAAO,UAAU,UAC1B,OAAO,OAAO,qBAAqB,aAA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ise<any[] |
|
|
46
|
+
}: HttpContext): Promise<any[] | Record<string, any> | Response>;
|
|
47
47
|
/**
|
|
48
48
|
* Get single record
|
|
49
49
|
*/
|
|
50
50
|
get({
|
|
51
51
|
request,
|
|
52
52
|
response
|
|
53
|
-
}: HttpContext): Promise<any[] |
|
|
53
|
+
}: HttpContext): Promise<any[] | Record<string, any> | Response>;
|
|
54
54
|
/**
|
|
55
55
|
* Create a new record
|
|
56
56
|
*/
|
|
@@ -78,14 +78,14 @@ declare abstract class Restful<T extends Model> implements RouteResource {
|
|
|
78
78
|
delete({
|
|
79
79
|
request,
|
|
80
80
|
response
|
|
81
|
-
}: HttpContext): Promise<any[] |
|
|
81
|
+
}: HttpContext): Promise<any[] | Record<string, any> | Response>;
|
|
82
82
|
/**
|
|
83
83
|
* Bulk delete records
|
|
84
84
|
*/
|
|
85
85
|
bulkDelete({
|
|
86
86
|
request,
|
|
87
87
|
response
|
|
88
|
-
}: HttpContext): Promise<any[] |
|
|
88
|
+
}: HttpContext): Promise<any[] | Record<string, any> | Response>;
|
|
89
89
|
/**
|
|
90
90
|
* Before create
|
|
91
91
|
*/
|
|
@@ -136,7 +136,7 @@ declare abstract class Restful<T extends Model> implements RouteResource {
|
|
|
136
136
|
* Call middleware for the given method
|
|
137
137
|
*
|
|
138
138
|
*/
|
|
139
|
-
protected callMiddleware(method: string, request: Request, response: Response, _record?: any): Promise<any[] |
|
|
139
|
+
protected callMiddleware(method: string, request: Request, response: Response, _record?: any): Promise<any[] | Record<string, any> | Response | undefined>;
|
|
140
140
|
}
|
|
141
141
|
//#endregion
|
|
142
142
|
export { Restful };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"restful.d.mts","names":[],"sources":["../../../../../../../core/src/restful/restful.ts"],"mappings":";;;;;;;;uBASsB,OAAA,WAAkB,KAAA,aAAkB,aAAA;;;;YAI9C,UAAA,EAAY,iBAAA;;AAJxB;;YASY,UAAA;EAT4B;;;EAAA,UAc5B,eAAA;EAUU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T,UAAA,GAAa,CAAA,GACZ,OAAA;EASyE;;;;;EAAA,UAAlE,OAAA,CAAQ,MAAA,iCAAuC,OAAA,EAAS,OAAA,GAAU,aAAA;EA5bpB;;;;EAAA,UAsdxC,cAAA,CACd,MAAA,UACA,OAAA,EAAS,OAAA,EACT,QAAA,EAAU,QAAA,EACV,OAAA,SAAa,OAAA,SAAA,MAAA,gBAAA,QAAA;AAAA"}
|
package/llms-full.txt
CHANGED
|
@@ -2372,7 +2372,7 @@ Password hashing (`hashPassword`) needs `bcryptjs`, which is its own install —
|
|
|
2372
2372
|
|
|
2373
2373
|
---
|
|
2374
2374
|
name: generate-openapi
|
|
2375
|
-
description: 'Generate an OpenAPI 3.1 document from the registered routes with `warlock generate.openapi` (default `storage/openapi/openapi.json`) and read it live in the dev-only API docs page at `/__warlock/docs`. Documents paths, path/query parameters, request bodies from Seal validation, responses from `handler.responseSchema`, 401/422 and bearer/cookie security from `authMiddleware()`. Triggers: `generate.openapi`, `openApiGeneratorCommand`, `buildOpenApiDocument`, `getDevelopmentOpenApiDocument`, `responseSchema`, `--include-pages`, `/__warlock/docs`; "OpenAPI", "Swagger", "API docs", "import my API into Postman or Insomnia", "document my routes". Skip: declaring response types on a handler — `@warlock.js/core/create-controller/SKILL.md`; the devtools dashboard — `@warlock.js/devtools/devtools-overview/SKILL.md`; listing routes — `@warlock.js/core/warlock-routes/SKILL.md`.'
|
|
2375
|
+
description: 'Generate an OpenAPI 3.1 document from the registered routes with `warlock generate.openapi` (default `storage/openapi/openapi.json`), write a Postman collection from it with `warlock generate.postman` (default `storage/postman/collection.json`), and read it live in the dev-only API docs page at `/__warlock/docs`. Documents paths, path/query parameters, request bodies from Seal validation, responses from `handler.responseSchema`, 401/422 and bearer/cookie security from `authMiddleware()`. Triggers: `generate.openapi`, `openApiGeneratorCommand`, `buildOpenApiDocument`, `getDevelopmentOpenApiDocument`, `generate.postman`, `openApiToPostmanCollection`, `getDevelopmentPostmanCollection`, `responseSchema`, `--include-pages`, `/__warlock/docs`; "OpenAPI", "Swagger", "API docs", "import my API into Postman or Insomnia", "document my routes". Skip: declaring response types on a handler — `@warlock.js/core/create-controller/SKILL.md`; the devtools dashboard — `@warlock.js/devtools/devtools-overview/SKILL.md`; listing routes — `@warlock.js/core/warlock-routes/SKILL.md`.'
|
|
2376
2376
|
---
|
|
2377
2377
|
|
|
2378
2378
|
# Warlock — generate an OpenAPI document
|
|
@@ -2466,6 +2466,34 @@ With `@warlock.js/devtools` installed (`warlock add devtools`), `warlock dev` se
|
|
|
2466
2466
|
|
|
2467
2467
|
The output is plain OpenAPI 3.1 JSON, so any tool that reads an OpenAPI file can use it: import `storage/openapi/openapi.json` into Postman or Insomnia (their Import action), or feed it to a client generator. Support for 3.1 is the tool's; if an old version refuses it, update the tool. Regenerate the file whenever routes change, or commit it if you publish it.
|
|
2468
2468
|
|
|
2469
|
+
## Postman
|
|
2470
|
+
|
|
2471
|
+
`warlock generate.postman` writes a Postman Collection v2.1.0. It is derived from the OpenAPI document (the same registration child and options as `generate.openapi`), never from the routes directly, so the collection and the OpenAPI file always agree.
|
|
2472
|
+
|
|
2473
|
+
```bash
|
|
2474
|
+
npx warlock generate.postman
|
|
2475
|
+
# Postman collection written to <root>/storage/postman/collection.json (3 folders, 17 requests). Import it in Postman and set the {{token}} variable.
|
|
2476
|
+
```
|
|
2477
|
+
|
|
2478
|
+
| Option | Default | Meaning |
|
|
2479
|
+
| ----------------- | ----------------------------------------- | ------------------------------------------------------------------ |
|
|
2480
|
+
| `--out`, `-o` | `storage/postman/collection.json` | Output file, relative to the project root. |
|
|
2481
|
+
| `--title` | `name` in `package.json` | Collection name; the collection id is a stable hash of it. |
|
|
2482
|
+
| `--server` | `http://<host>:<port>` from the `http` config | Value of the `{{baseUrl}}` variable. |
|
|
2483
|
+
| `--include-pages` | off | Also include page (SSR) routes. |
|
|
2484
|
+
|
|
2485
|
+
What the collection contains:
|
|
2486
|
+
|
|
2487
|
+
- One folder per tag (the first path segment), in order of first appearance; untagged operations sit at the root.
|
|
2488
|
+
- One request per operation, named by its summary (the route `label`) or `operationId`. `{id}` becomes the `:id` path variable; query parameters are rows (optional ones disabled); the operation description and parameter descriptions carry over.
|
|
2489
|
+
- A JSON body with a `Content-Type` header and an **example generated from the schema** (strings by format such as `email` or `date-time`, `0`, `false`, the first `enum` value, one array item, resources resolved with cycles cut). A multipart body becomes form-data with file rows.
|
|
2490
|
+
- A saved response for every declared status, with an example body.
|
|
2491
|
+
- Collection variables `baseUrl` and `token`. When any route is guarded by `authMiddleware()`, the collection uses bearer auth with `{{token}}`; public routes are set to no auth so the token is not sent. A cookie-only route has a description note: Postman keeps cookies per domain, so sign in against `{{baseUrl}}` first.
|
|
2492
|
+
|
|
2493
|
+
To use it: in Postman choose **Import** and pick the file, open the collection's **Variables** tab, paste a token into `token` (for example the `token` from your login response), and adjust `baseUrl` if needed. Regenerate and re-import when routes change.
|
|
2494
|
+
|
|
2495
|
+
Programmatic use: `openApiToPostmanCollection(document, { title?, baseUrl? })` is exported from `@warlock.js/core` (pure and deterministic), and `getDevelopmentPostmanCollection()` returns `{ collection, warnings }` for the running dev process (it throws outside `warlock dev`, like `getDevelopmentOpenApiDocument`).
|
|
2496
|
+
|
|
2469
2497
|
## Programmatic use
|
|
2470
2498
|
|
|
2471
2499
|
`buildOpenApiDocument(routes, context)` is exported from `@warlock.js/core`: a pure function from `router.list()` routes to `{ document, warnings }`. `context` carries `info`, `servers`, `includePages`, `resolveResourceName` and `validationResponse`. Use it to build the document inside your own tooling; the CLI uses the same function inside the registration child.
|
package/llms.txt
CHANGED
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
- [create-module](@warlock.js/core/create-module/SKILL.md): Scaffold a new feature module under `src/app/<name>/` via `warlock generate.module` and the follow-up generators for controllers, models, repositories, resources, and validation schemas. Triggers: `warlock generate.module`, `generate.controller`, `generate.service`, `generate.model`, `generate.repository`, `generate.resource`, `generate.migration`, `--minimal`, `gen.m`; "scaffold a new module", "create CRUD bootstrap", "add a controller to a module", "generate a model"; typical CLI `npx warlock generate.module <name>`. Skip: framework-wide layout rules — `@warlock.js/core/warlock-conventions/SKILL.md`; routes file shape — `@warlock.js/core/register-route/SKILL.md`; controller shape — `@warlock.js/core/create-controller/SKILL.md`; competing tooling: `@nestjs/cli`, `hygen`, hand-rolled folder layouts.
|
|
16
16
|
- [define-resource](@warlock.js/core/define-resource/SKILL.md): Map model fields to wire-shape via `defineResource()` or `Resource` subclasses. Output-only — never put business logic, hydration, or reconciliation in a resource. Also covers the typed output: `ResourceOutput<typeof R>`, `defineResource<Out>()`, `Serialized<T, W>` and `ModelResourceRegistry`. Triggers: `defineResource`, `Resource`, `RegisterResource`, `toJSON`, `ResourceOutput`, `Serialized`, `ModelResourceRegistry`, `"self"`, `"localized"`, `"uploadsUrl"`; "shape an API response", "type a resource's output", "what does the client receive", "nest related resources", "rename a field on output", "self-referential tree resource"; typical import `import { defineResource } from "@warlock.js/core"`. Skip: localized columns — `@warlock.js/core/use-localization/SKILL.md`; URL casting — `@warlock.js/core/build-url/SKILL.md`; controller side — `@warlock.js/core/create-controller/SKILL.md`; competing libs `@nestjs/swagger` `@ApiProperty`, `class-transformer`, hand-rolled DTO mappers.
|
|
17
17
|
- [encrypt-data](@warlock.js/core/encrypt-data/SKILL.md): Reversible AES-256-GCM `encrypt` / `decrypt` for secrets you need to read back; one-way HMAC-SHA256 `hmacHash` for deterministic fingerprints (lookup/dedup of encrypted columns). Keys come from `src/config/encryption.ts`. Triggers: `encrypt`, `decrypt`, `hmacHash`, `EncryptionConfigurations`, `APP_ENCRYPTION_KEY`, `APP_HMAC_KEY`; "store an API key reversibly", "fingerprint an encrypted column for lookup", "AES-256-GCM secret", "HMAC-SHA256 dedup key"; typical import `import { encrypt, decrypt, hmacHash } from "@warlock.js/core"`. Skip: password hashing — `@warlock.js/core/hash-password/SKILL.md`; config wiring — `@warlock.js/core/configure-app/SKILL.md`; competing libs Node `crypto` direct, `crypto-js`, `libsodium-wrappers`.
|
|
18
|
-
- [generate-openapi](@warlock.js/core/generate-openapi/SKILL.md): Generate an OpenAPI 3.1 document from the registered routes with `warlock generate.openapi` (default `storage/openapi/openapi.json`) and read it live in the dev-only API docs page at `/__warlock/docs`. Documents paths, path/query parameters, request bodies from Seal validation, responses from `handler.responseSchema`, 401/422 and bearer/cookie security from `authMiddleware()`. Triggers: `generate.openapi`, `openApiGeneratorCommand`, `buildOpenApiDocument`, `getDevelopmentOpenApiDocument`, `responseSchema`, `--include-pages`, `/__warlock/docs`; "OpenAPI", "Swagger", "API docs", "import my API into Postman or Insomnia", "document my routes". Skip: declaring response types on a handler — `@warlock.js/core/create-controller/SKILL.md`; the devtools dashboard — `@warlock.js/devtools/devtools-overview/SKILL.md`; listing routes — `@warlock.js/core/warlock-routes/SKILL.md`.
|
|
18
|
+
- [generate-openapi](@warlock.js/core/generate-openapi/SKILL.md): Generate an OpenAPI 3.1 document from the registered routes with `warlock generate.openapi` (default `storage/openapi/openapi.json`), write a Postman collection from it with `warlock generate.postman` (default `storage/postman/collection.json`), and read it live in the dev-only API docs page at `/__warlock/docs`. Documents paths, path/query parameters, request bodies from Seal validation, responses from `handler.responseSchema`, 401/422 and bearer/cookie security from `authMiddleware()`. Triggers: `generate.openapi`, `openApiGeneratorCommand`, `buildOpenApiDocument`, `getDevelopmentOpenApiDocument`, `generate.postman`, `openApiToPostmanCollection`, `getDevelopmentPostmanCollection`, `responseSchema`, `--include-pages`, `/__warlock/docs`; "OpenAPI", "Swagger", "API docs", "import my API into Postman or Insomnia", "document my routes". Skip: declaring response types on a handler — `@warlock.js/core/create-controller/SKILL.md`; the devtools dashboard — `@warlock.js/devtools/devtools-overview/SKILL.md`; listing routes — `@warlock.js/core/warlock-routes/SKILL.md`.
|
|
19
19
|
- [hash-password](@warlock.js/core/hash-password/SKILL.md): One-way bcrypt password hashing — `hashPassword` / `verifyPassword`, plus the declarative `useHashedPassword()` schema transformer that auto-hashes a model's password field on save. Salt rounds come from `src/config/encryption.ts`. Triggers: `hashPassword`, `verifyPassword`, `useHashedPassword`, `password.salt`, `bcryptjs`; "hash a user password", "verify login credentials", "auto-hash on save", "rotate a password"; typical import `import { hashPassword, verifyPassword } from "@warlock.js/core"`. Skip: reversible secrets — `@warlock.js/core/encrypt-data/SKILL.md`; the other transformers — `@warlock.js/core/use-model-transformers/SKILL.md`; config wiring — `@warlock.js/core/configure-app/SKILL.md`; competing libs `bcrypt` native, `argon2`, `scrypt`.
|
|
20
20
|
- [health-checks](@warlock.js/core/health-checks/SKILL.md): Built-in liveness (`/health`) and readiness (`/ready`) endpoints plus graceful HTTP request draining for zero-downtime deploys — the `health` registry (`health.addCheck`/`removeCheck`), the `http.health.*` and `http.gracefulShutdown.*` config, and how readiness ties into `Application.isShuttingDown`. Triggers: `health`, `health.addCheck`, `health.removeCheck`, `HealthCheck`, `/health`, `/ready`, `http.health`, `http.gracefulShutdown`, `forceCloseConnections`, "liveness probe", "readiness probe", "graceful shutdown", "drain in-flight requests", "zero-downtime deploy", "kubernetes health check", "503 until ready"; typical import `import { health } from "@warlock.js/core"`. Skip: the `Application.onShutdown` / `onceBooted` lifecycle hooks — `@warlock.js/core/use-app-context/SKILL.md`; maintenance-mode 503s — `@warlock.js/core/use-middleware/SKILL.md`; connector lifecycle — `@warlock.js/core/add-connector/SKILL.md`; competing libs `@fastify/under-pressure`, `terminus`, hand-rolled `/health` controllers.
|
|
21
21
|
- [lower-stage3-decorators](@warlock.js/core/lower-stage3-decorators/SKILL.md): Vite/Vitest plugin `lowerStage3Decorators()` that lowers TC39 Stage-3 (native) decorators with esbuild before oxc / the SSR rewrite mangles them — so `@RegisterModel`-decorated Cascade models load under Vitest 4 / Vite 8. Triggers: `lowerStage3Decorators`, "SyntaxError: Invalid or unexpected token" on a decorated class, "@(0, __vite_ssr_import__.X)()", "decorator crashes vitest", "models won't load in tests", "Vite 8 oxc decorators"; typical import `import { lowerStage3Decorators } from "@warlock.js/core/vite"` in `vite.config.ts` / `vitest.config.ts`. Skip: writing the tests themselves — `@warlock.js/core/test-service/SKILL.md` / `@warlock.js/core/test-http/SKILL.md`; runtime migrations — `@warlock.js/cascade/write-migration/SKILL.md`.
|
package/package.json
CHANGED
|
@@ -25,12 +25,12 @@
|
|
|
25
25
|
"@mongez/slug": "^1.0.7",
|
|
26
26
|
"@mongez/supportive-is": "^3.0.0",
|
|
27
27
|
"@mongez/time-wizard": "^1.0.6",
|
|
28
|
-
"@warlock.js/cache": "5.
|
|
29
|
-
"@warlock.js/cascade": "5.
|
|
30
|
-
"@warlock.js/context": "5.
|
|
31
|
-
"@warlock.js/fs": "5.
|
|
32
|
-
"@warlock.js/logger": "5.
|
|
33
|
-
"@warlock.js/seal": "5.
|
|
28
|
+
"@warlock.js/cache": "5.28.0",
|
|
29
|
+
"@warlock.js/cascade": "5.28.0",
|
|
30
|
+
"@warlock.js/context": "5.28.0",
|
|
31
|
+
"@warlock.js/fs": "5.28.0",
|
|
32
|
+
"@warlock.js/logger": "5.28.0",
|
|
33
|
+
"@warlock.js/seal": "5.28.0",
|
|
34
34
|
"bcryptjs": "^3.0.3",
|
|
35
35
|
"chokidar": "^5.0.0",
|
|
36
36
|
"dayjs": "^1.11.19",
|
|
@@ -52,11 +52,11 @@
|
|
|
52
52
|
"@aws-sdk/lib-storage": "^3.955.0",
|
|
53
53
|
"@aws-sdk/s3-request-presigner": "^3.955.0",
|
|
54
54
|
"@react-email/render": "^2.0.5",
|
|
55
|
-
"@warlock.js/access": "5.
|
|
56
|
-
"@warlock.js/ai": "5.
|
|
57
|
-
"@warlock.js/herald": "5.
|
|
58
|
-
"@warlock.js/notifications": "5.
|
|
59
|
-
"@warlock.js/devtools": "5.
|
|
55
|
+
"@warlock.js/access": "5.28.0",
|
|
56
|
+
"@warlock.js/ai": "5.28.0",
|
|
57
|
+
"@warlock.js/herald": "5.28.0",
|
|
58
|
+
"@warlock.js/notifications": "5.28.0",
|
|
59
|
+
"@warlock.js/devtools": "5.28.0",
|
|
60
60
|
"nodemailer": "^8.0.5",
|
|
61
61
|
"react": "^19.2.3",
|
|
62
62
|
"react-dom": "^19.2.3",
|
|
@@ -127,7 +127,7 @@
|
|
|
127
127
|
],
|
|
128
128
|
"author": "hassanzohdy",
|
|
129
129
|
"license": "MIT",
|
|
130
|
-
"version": "5.
|
|
130
|
+
"version": "5.28.0",
|
|
131
131
|
"type": "module",
|
|
132
132
|
"main": "./esm/index.mjs",
|
|
133
133
|
"module": "./esm/index.mjs",
|