@warlock.js/core 5.23.2 → 5.25.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 +36 -1
- package/bin/warlock.js +0 -0
- package/esm/application/application.d.mts +21 -0
- package/esm/application/application.d.mts.map +1 -1
- package/esm/application/application.mjs +29 -1
- package/esm/application/application.mjs.map +1 -1
- package/esm/application/boot-signal.d.mts +2 -1
- package/esm/application/boot-signal.d.mts.map +1 -1
- package/esm/application/boot-signal.mjs.map +1 -1
- package/esm/application/index.d.mts +1 -0
- package/esm/application/index.mjs +1 -0
- package/esm/application/roles.d.mts +72 -0
- package/esm/application/roles.d.mts.map +1 -0
- package/esm/application/roles.mjs +124 -0
- package/esm/application/roles.mjs.map +1 -0
- package/esm/cli/commands/add.command.mjs.map +1 -1
- package/esm/cli/commands/create-database.command.mjs.map +1 -1
- package/esm/cli/commands/dev-server.command.mjs.map +1 -1
- package/esm/cli/commands/doctor/boot-for-diagnostics.mjs.map +1 -1
- package/esm/cli/commands/drop-tables.command.mjs.map +1 -1
- package/esm/cli/commands/generate/utils/path-resolver.mjs.map +1 -1
- package/esm/cli/commands/migrate.command.mjs.map +1 -1
- package/esm/cli/commands/routes.command.mjs.map +1 -1
- package/esm/cli/commands/seed.command.mjs.map +1 -1
- package/esm/cli/commands/start-production.command.mjs +54 -5
- package/esm/cli/commands/start-production.command.mjs.map +1 -1
- package/esm/cli/commands/storage-put.action.mjs.map +1 -1
- package/esm/cli/commands/storage-put.command.mjs.map +1 -1
- package/esm/cli/commands/typings-generator.command.mjs +17 -1
- package/esm/cli/commands/typings-generator.command.mjs.map +1 -1
- package/esm/cli/commands/update.command.mjs.map +1 -1
- package/esm/cli/commands-loader.mjs.map +1 -1
- package/esm/config/config-loader.d.mts.map +1 -1
- package/esm/config/config-loader.mjs +3 -1
- package/esm/config/config-loader.mjs.map +1 -1
- package/esm/connectors/connectors-manager.mjs.map +1 -1
- package/esm/connectors/database-connector.mjs.map +1 -1
- package/esm/connectors/herald-connector.mjs.map +1 -1
- package/esm/connectors/http-connector.d.mts.map +1 -1
- package/esm/connectors/http-connector.mjs +7 -0
- package/esm/connectors/http-connector.mjs.map +1 -1
- package/esm/connectors/logger-connector.mjs.map +1 -1
- package/esm/connectors/mail-connector.mjs.map +1 -1
- package/esm/connectors/types.d.mts +8 -0
- package/esm/connectors/types.d.mts.map +1 -1
- package/esm/connectors/types.mjs.map +1 -1
- package/esm/database/create-database-action.mjs.map +1 -1
- package/esm/database/drop-tables-action.mjs.map +1 -1
- package/esm/database/migrate-action.mjs +2 -1
- package/esm/database/migrate-action.mjs.map +1 -1
- package/esm/database/models/database-log/database-log.mjs.map +1 -1
- package/esm/database/seed-command-action.mjs +2 -1
- package/esm/database/seed-command-action.mjs.map +1 -1
- package/esm/dev-server/dependency-graph.mjs.map +1 -1
- package/esm/dev-server/development-server.mjs +2 -0
- package/esm/dev-server/development-server.mjs.map +1 -1
- package/esm/dev-server/files-orchestrator.mjs.map +1 -1
- package/esm/dev-server/layer-executor.mjs.map +1 -1
- package/esm/dev-server/manifest-manager.mjs.map +1 -1
- package/esm/dev-server/module-loader.mjs +10 -5
- package/esm/dev-server/module-loader.mjs.map +1 -1
- package/esm/dev-server/register-installed-devtools.mjs +47 -0
- package/esm/dev-server/register-installed-devtools.mjs.map +1 -0
- package/esm/dev-server/run-connector-typings.mjs +28 -0
- package/esm/dev-server/run-connector-typings.mjs.map +1 -0
- package/esm/dev-server/special-file-patterns.mjs +3 -1
- package/esm/dev-server/special-file-patterns.mjs.map +1 -1
- package/esm/dev-server/special-files-collector.d.mts +2 -2
- package/esm/dev-server/special-files-collector.d.mts.map +1 -1
- package/esm/dev-server/special-files-collector.mjs +7 -4
- package/esm/dev-server/special-files-collector.mjs.map +1 -1
- package/esm/encryption/password.mjs.map +1 -1
- package/esm/generations/add-command.action.mjs +3 -1
- package/esm/generations/add-command.action.mjs.map +1 -1
- package/esm/generations/features/access.feature.mjs.map +1 -1
- package/esm/generations/features/ai-anthropic.feature.mjs.map +1 -1
- package/esm/generations/features/ai-bedrock.feature.mjs.map +1 -1
- package/esm/generations/features/ai-google.feature.mjs.map +1 -1
- package/esm/generations/features/ai-ollama.feature.mjs.map +1 -1
- package/esm/generations/features/ai-openai.feature.mjs.map +1 -1
- package/esm/generations/features/ai-panoptic.feature.mjs.map +1 -1
- package/esm/generations/features/ai-tools.feature.mjs.map +1 -1
- package/esm/generations/features/ai-workspace.feature.mjs.map +1 -1
- package/esm/generations/features/ai.feature.mjs.map +1 -1
- package/esm/generations/features/devtools.feature.mjs +23 -0
- package/esm/generations/features/devtools.feature.mjs.map +1 -0
- package/esm/generations/features/herald.feature.mjs.map +1 -1
- package/esm/generations/features/image.feature.mjs.map +1 -1
- package/esm/generations/features/index.mjs +2 -0
- package/esm/generations/features/index.mjs.map +1 -1
- package/esm/generations/features/mail.feature.mjs.map +1 -1
- package/esm/generations/features/mongodb.feature.mjs.map +1 -1
- package/esm/generations/features/notifications.feature.mjs.map +1 -1
- package/esm/generations/features/postgres.feature.mjs.map +1 -1
- package/esm/generations/features/react-email.feature.mjs.map +1 -1
- package/esm/generations/features/react.feature.mjs.map +1 -1
- package/esm/generations/features/redis.feature.mjs.map +1 -1
- package/esm/generations/features/s3.feature.mjs.map +1 -1
- package/esm/generations/features/scheduler.feature.mjs.map +1 -1
- package/esm/generations/features/ses.feature.mjs.map +1 -1
- package/esm/generations/features/socket.feature.mjs.map +1 -1
- package/esm/generations/features/test.feature.mjs +6 -2
- package/esm/generations/features/test.feature.mjs.map +1 -1
- package/esm/generations/features/types.mjs.map +1 -1
- package/esm/generations/features/web.feature.mjs.map +1 -1
- package/esm/http/database/RequestLog.mjs.map +1 -1
- package/esm/http/index.d.mts +2 -1
- package/esm/http/index.mjs +2 -1
- package/esm/http/middleware/inject-request-context.d.mts.map +1 -1
- package/esm/http/middleware/inject-request-context.mjs +9 -1
- package/esm/http/middleware/inject-request-context.mjs.map +1 -1
- package/esm/http/request.d.mts +7 -0
- package/esm/http/request.d.mts.map +1 -1
- package/esm/http/request.mjs +8 -0
- package/esm/http/request.mjs.map +1 -1
- package/esm/http/response.d.mts +5 -5
- package/esm/http/response.d.mts.map +1 -1
- package/esm/http/response.mjs.map +1 -1
- package/esm/http/server-rebuilt.d.mts +20 -0
- package/esm/http/server-rebuilt.d.mts.map +1 -0
- package/esm/http/server-rebuilt.mjs +21 -0
- package/esm/http/server-rebuilt.mjs.map +1 -0
- package/esm/http/tracing/index.mjs +1 -1
- package/esm/http/tracing/tracing-dispatcher.d.mts +13 -6
- package/esm/http/tracing/tracing-dispatcher.d.mts.map +1 -1
- package/esm/http/tracing/tracing-dispatcher.mjs +46 -14
- package/esm/http/tracing/tracing-dispatcher.mjs.map +1 -1
- package/esm/http/tracing/tracing.type.d.mts +2 -1
- package/esm/http/tracing/tracing.type.d.mts.map +1 -1
- package/esm/http/types.d.mts +9 -0
- package/esm/http/types.d.mts.map +1 -1
- package/esm/image/image.mjs.map +1 -1
- package/esm/index.d.mts +4 -2
- package/esm/index.mjs +4 -2
- package/esm/loader/app-module-importer.d.mts +17 -0
- package/esm/loader/app-module-importer.d.mts.map +1 -0
- package/esm/loader/app-module-importer.mjs +20 -0
- package/esm/loader/app-module-importer.mjs.map +1 -0
- package/esm/logger/logger.mjs.map +1 -1
- package/esm/mail/events.d.mts +7 -0
- package/esm/mail/events.d.mts.map +1 -1
- package/esm/mail/events.mjs +7 -0
- package/esm/mail/events.mjs.map +1 -1
- package/esm/mail/send-mail.d.mts.map +1 -1
- package/esm/mail/send-mail.mjs +23 -2
- package/esm/mail/send-mail.mjs.map +1 -1
- package/esm/mail/types.d.mts +5 -1
- package/esm/mail/types.d.mts.map +1 -1
- package/esm/mail/types.mjs.map +1 -1
- package/esm/manifest/manifest-manager.mjs.map +1 -1
- package/esm/production/build-contributions.mjs +19 -3
- package/esm/production/build-contributions.mjs.map +1 -1
- package/esm/production/production-builder.mjs +28 -8
- package/esm/production/production-builder.mjs.map +1 -1
- package/esm/production/production-supervisor.mjs +6 -0
- package/esm/production/production-supervisor.mjs.map +1 -1
- package/esm/production/resolve-build-config.d.mts +1 -1
- package/esm/production/resolve-build-config.mjs +15 -0
- package/esm/production/resolve-build-config.mjs.map +1 -1
- package/esm/production/route-registration-child.mjs +14 -2
- package/esm/production/route-registration-child.mjs.map +1 -1
- package/esm/production/route-registration-snapshot.mjs +9 -2
- package/esm/production/route-registration-snapshot.mjs.map +1 -1
- package/esm/resource/resource-field-builder.mjs +1 -1
- package/esm/resource/resource-field-builder.mjs.map +1 -1
- package/esm/resource/resource.d.mts +5 -0
- package/esm/resource/resource.d.mts.map +1 -1
- package/esm/resource/resource.mjs +17 -6
- package/esm/resource/resource.mjs.map +1 -1
- package/esm/router/router.d.mts.map +1 -1
- package/esm/router/router.mjs +1 -0
- package/esm/router/router.mjs.map +1 -1
- package/esm/router/types.d.mts +2 -1
- package/esm/router/types.d.mts.map +1 -1
- package/esm/tests/index.d.mts +3 -2
- package/esm/tests/index.mjs +3 -2
- package/esm/tests/vitest-setup.d.mts +16 -1
- package/esm/tests/vitest-setup.d.mts.map +1 -1
- package/esm/tests/vitest-setup.mjs +20 -2
- package/esm/tests/vitest-setup.mjs.map +1 -1
- package/esm/use-cases/use-case-events.mjs.map +1 -1
- package/esm/utils/is-test-file.mjs +15 -0
- package/esm/utils/is-test-file.mjs.map +1 -0
- package/esm/utils/normalized-path.d.mts +3 -1
- package/esm/utils/normalized-path.d.mts.map +1 -1
- package/esm/utils/normalized-path.mjs +4 -2
- package/esm/utils/normalized-path.mjs.map +1 -1
- package/esm/utils/paths.mjs.map +1 -1
- package/esm/validation/plugins/database-plugin.mjs.map +1 -1
- package/esm/validation/validateAll.mjs +9 -3
- package/esm/validation/validateAll.mjs.map +1 -1
- package/esm/warlock-config/default-configurations.mjs +1 -0
- package/esm/warlock-config/default-configurations.mjs.map +1 -1
- package/esm/warlock-config/types.d.mts +7 -0
- package/esm/warlock-config/types.d.mts.map +1 -1
- package/esm/warlock-config/warlock-config.manager.mjs.map +1 -1
- package/llms-full.txt +264 -139
- package/package.json +15 -11
- package/skills/configure-app/SKILL.md +2 -0
- package/skills/define-resource/SKILL.md +4 -0
- package/skills/request-tracing/SKILL.md +38 -15
- package/skills/run-app/SKILL.md +71 -34
- package/skills/send-mail/SKILL.md +55 -25
- package/skills/test-http/SKILL.md +19 -8
- package/skills/test-service/SKILL.md +61 -40
- package/skills/warlock-conventions/SKILL.md +26 -18
- package/skills/write-cli-command/SKILL.md +50 -45
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resource-field-builder.mjs","names":[],"sources":["../../../../../../../core/src/resource/resource-field-builder.ts"],"sourcesContent":["import { isObject } from \"@mongez/supportive-is\";\nimport dayjs from \"dayjs\";\nimport relativeTime from \"dayjs/plugin/relativeTime.js\";\nimport { storage } from \"../storage\";\n\n// `humanTime` date options call dayjs(...).fromNow(), which lives in the\n// relativeTime plugin. dayjs.extend is idempotent (a plugin registers itself\n// once), so extending here at module load is safe to repeat.\ndayjs.extend(relativeTime);\nimport { uploadsUrl, url } from \"../utils/urls\";\nimport { type LocalizedObject } from \"./../utils/get-localized\";\nimport {\n type ResourceFieldBuilderDateOutputOptions,\n type ResourceOutputValueCastType,\n} from \"./types\";\n\nexport class ResourceFieldBuilder {\n /**\n * Field value\n */\n protected fieldValue?: unknown;\n\n /**\n * Whether the value is nullable\n * If set to false and value is null, it will be returned as undefined\n */\n protected isNullable = false;\n\n /**\n * Whether this field is an array\n * When true, transform() maps over each element using the base type\n */\n protected isArrayField = false;\n\n /**\n * Default value\n */\n protected defaultValue?: unknown;\n\n /**\n * Date format\n */\n protected dateFormat = \"DD-MM-YYYY hh:mm:ss A\";\n\n /**\n * Input key\n */\n protected inputKeyToUse?: string;\n\n /**\n * Add a condition before transforming the value\n */\n protected condition?: () => boolean;\n\n /**\n * Define how date fields are returned\n * If type of the date options is string then it will be returned as a string\n * otherwise it will be returned as an object contains the date options\n */\n protected dateOptionsInput: ResourceFieldBuilderDateOutputOptions = {\n format: true,\n timestamp: true,\n timezone: false,\n locale: false,\n offset: false,\n humanTime: true,\n iso: true,\n };\n\n /**\n * Constructor\n */\n public constructor(protected readonly type: ResourceOutputValueCastType) {\n //\n }\n\n /**\n * Parse a cast type string (including suffixes) into a configured builder.\n * Suffix order: [] before ? (e.g. \"string[]?\")\n * Parsing strips right-to-left: ? first, then [].\n */\n public static fromCastType(castType: string): ResourceFieldBuilder {\n let baseType = castType;\n let nullable = false;\n let isArray = false;\n\n if (baseType.endsWith(\"?\")) {\n nullable = true;\n baseType = baseType.slice(0, -1);\n }\n\n if (baseType.endsWith(\"[]\")) {\n isArray = true;\n baseType = baseType.slice(0, -2);\n }\n\n const builder = new ResourceFieldBuilder(baseType as ResourceOutputValueCastType);\n if (nullable) builder.nullable();\n if (isArray) builder.array();\n return builder;\n }\n\n /**\n * Set input key\n * Will be used in transformation if provided\n */\n public setInputKey(key: string) {\n this.inputKeyToUse = key;\n\n return this;\n }\n\n /**\n * Add a condition before transforming the value\n */\n public when(condition: () => boolean) {\n this.condition = condition;\n return this;\n }\n\n /**\n * Set whether the value is nullable\n */\n public nullable() {\n this.isNullable = true;\n return this;\n }\n\n /**\n * Mark this field as an array\n * transform() will map over each element using the base type\n */\n public array() {\n this.isArrayField = true;\n return this;\n }\n\n /**\n * Get input key\n */\n public getInputKey() {\n return this.inputKeyToUse;\n }\n\n /**\n * Set default value\n */\n public default(value: unknown) {\n this.defaultValue = value;\n\n return this;\n }\n\n /**\n * Set field format\n */\n public format(format: string) {\n this.dateFormat = format;\n\n return this;\n }\n\n /**\n * Set date options\n * This will override current date options\n */\n public dateOptions(options: ResourceFieldBuilderDateOutputOptions) {\n this.dateOptionsInput = options;\n\n return this;\n }\n\n /**\n * Transform the value.\n * When isArrayField is true, maps over each element using transformSingleValue.\n */\n public transform(value: any, locale?: string) {\n if (this.isArrayField) {\n if (!Array.isArray(value)) {\n return this.isNullable ? null : [];\n }\n\n return value\n .map((item) => this.transformSingleValue(item, locale))\n .filter((v) => v !== undefined);\n }\n\n return this.transformSingleValue(value, locale);\n }\n\n /**\n * Transform a single value according to the base type.\n */\n protected transformSingleValue(value: any, locale?: string) {\n if (value === undefined || value === null) {\n return this.isNullable ? null : this.defaultValue;\n }\n\n if (this.condition && !this.condition()) {\n return this.isNullable ? null : this.defaultValue;\n }\n\n switch (this.type) {\n case \"string\":\n return String(value);\n case \"number\": {\n const num = Number(value);\n return isNaN(num) ? (this.isNullable ? null : undefined) : num;\n }\n case \"boolean\":\n return Boolean(value);\n case \"float\": {\n const float = parseFloat(value);\n return isNaN(float) ? (this.isNullable ? null : undefined) : float;\n }\n\n case \"int\": {\n const int = parseInt(value);\n return isNaN(int) ? (this.isNullable ? null : undefined) : int;\n }\n\n case \"date\":\n return this.transformDate(value as string | Date, locale);\n case \"localized\":\n return this.transformLocalized(value as LocalizedObject[], locale);\n case \"url\":\n return url(value as string);\n case \"uploadsUrl\":\n return uploadsUrl(value as string);\n case \"storageUrl\":\n return storage.url(value as string);\n case \"object\":\n return isObject(value) && !Array.isArray(value) && Object.keys(value).length > 0\n ? value\n : this.isNullable\n ? null\n : undefined;\n case \"array\":\n return Array.isArray(value) ? value : this.isNullable ? null : undefined;\n }\n }\n\n /**\n * Transform date value\n */\n protected transformDate(value: string | Date, locale?: string) {\n // Bad data (\"\" or garbage) must not throw and turn the response into a 500\n if (!dayjs((value as any)?.iso || value).isValid()) {\n return this.isNullable ? null : undefined;\n }\n\n if (typeof this.dateOptionsInput === \"string\") {\n if (this.dateOptionsInput === \"format\") {\n return dayjs(value).format(this.dateFormat);\n }\n\n if (this.dateOptionsInput === \"iso\") {\n return dayjs(value).toISOString();\n }\n\n if (this.dateOptionsInput === \"timestamp\") {\n return dayjs(value).valueOf();\n }\n\n if (this.dateOptionsInput === \"humanTime\") {\n return (dayjs as any)(value).fromNow();\n }\n\n if (this.dateOptionsInput === \"locale\") {\n if (!locale) {\n return dayjs(value).format(this.dateFormat);\n }\n\n return dayjs(value).locale(locale).format(this.dateFormat);\n }\n }\n\n // now manage it as an object based on date options what's marked as true\n const output: {\n format?: string;\n timestamp?: number;\n humanTime?: string;\n locale?: string;\n iso?: string;\n } = {};\n\n let dayjsObject = dayjs((value as any)?.iso || value);\n\n if (locale) {\n dayjsObject = dayjsObject.locale(locale);\n }\n\n if (this.dateOptionsInput.iso) {\n output.iso = dayjsObject.toISOString();\n }\n\n if (this.dateOptionsInput.format) {\n output.format = dayjsObject.format(this.dateFormat);\n }\n\n if (this.dateOptionsInput.timestamp) {\n output.timestamp = dayjsObject.valueOf();\n }\n\n if (this.dateOptionsInput.humanTime) {\n output.humanTime = (dayjsObject as any).fromNow();\n }\n\n if (this.dateOptionsInput.locale) {\n output.locale = dayjsObject.format(this.dateFormat);\n }\n\n if (this.dateOptionsInput.iso) {\n output.iso = dayjsObject.toISOString();\n }\n\n return output;\n }\n\n /**\n * Transform localized value\n */\n protected transformLocalized(value: LocalizedObject[] | string, locale?: string) {\n if (typeof value === \"string\") {\n return value;\n }\n\n if (!locale) {\n return value[0]?.value || value;\n }\n\n return value.find((item) => item.localeCode === locale)?.value;\n }\n}\n"],"mappings":";;;;;;;;AAQA,MAAM,OAAO,YAAY;AAQzB,IAAa,uBAAb,MAAa,qBAAqB;;;;CAwDhC,AAAO,YAAY,AAAmB,MAAmC;EAAnC;oBA9Cf;sBAME;oBAUF;0BAiB6C;GAClE,QAAQ;GACR,WAAW;GACX,UAAU;GACV,QAAQ;GACR,QAAQ;GACR,WAAW;GACX,KAAK;EACP;CAOA;;;;;;CAOA,OAAc,aAAa,UAAwC;EACjE,IAAI,WAAW;EACf,IAAI,WAAW;EACf,IAAI,UAAU;EAEd,IAAI,SAAS,SAAS,GAAG,GAAG;GAC1B,WAAW;GACX,WAAW,SAAS,MAAM,GAAG,EAAE;EACjC;EAEA,IAAI,SAAS,SAAS,IAAI,GAAG;GAC3B,UAAU;GACV,WAAW,SAAS,MAAM,GAAG,EAAE;EACjC;EAEA,MAAM,UAA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K,CAAC,CAAC,OAAO,KAAK,UAAU;IAG5C,OAAO,MAAM,KAAK,CAAC,CAAC,OAAO,MAAM,CAAC,CAAC,OAAO,KAAK,UAAU;GAC3D;EACF;EAGA,MAAM,SAMF,CAAC;EAEL,IAAI,cAAc,MAAO,OAAe,OAAO,KAAK;EAEpD,IAAI,QACF,cAAc,YAAY,OAAO,MAAM;EAGzC,IAAI,KAAK,iBAAiB,KACxB,OAAO,MAAM,YAAY,YAAY;EAGvC,IAAI,KAAK,iBAAiB,QACxB,OAAO,SAAS,YAAY,OAAO,KAAK,UAAU;EAGpD,IAAI,KAAK,iBAAiB,WACxB,OAAO,YAAY,YAAY,QAAQ;EAGzC,IAAI,KAAK,iBAAiB,WACxB,OAAO,YAAa,YAAoB,QAAQ;EAGlD,IAAI,KAAK,iBAAiB,QACxB,OAAO,SAAS,YAAY,OAAO,KAAK,UAAU;EAGpD,IAAI,KAAK,iBAAiB,KACxB,OAAO,MAAM,YAAY,YAAY;EAGvC,OAAO;CACT;;;;CAKA,AAAU,mBAAmB,OAAmC,QAAiB;EAC/E,IAAI,OAAO,UAAU,UACnB,OAAO;EAGT,IAAI,CAAC,QACH,OAAO,MAAM,EAAE,EAAE,SAAS;EAG5B,OAAO,MAAM,MAAM,SAAS,KAAK,eAAe,MAAM,CAAC,EAAE;CAC3D;AACF"}
|
|
1
|
+
{"version":3,"file":"resource-field-builder.mjs","names":[],"sources":["../../../../../../../core/src/resource/resource-field-builder.ts"],"sourcesContent":["import { isObject } from \"@mongez/supportive-is\";\nimport dayjs from \"dayjs\";\nimport relativeTime from \"dayjs/plugin/relativeTime.js\";\nimport { storage } from \"../storage\";\n\n// `humanTime` date options call dayjs(...).fromNow(), which lives in the\n// relativeTime plugin. dayjs.extend is idempotent (a plugin registers itself\n// once), so extending here at module load is safe to repeat.\ndayjs.extend(relativeTime);\nimport { uploadsUrl, url } from \"../utils/urls\";\nimport { type LocalizedObject } from \"./../utils/get-localized\";\nimport {\n type ResourceFieldBuilderDateOutputOptions,\n type ResourceOutputValueCastType,\n} from \"./types\";\n\nexport class ResourceFieldBuilder {\n /**\n * Field value\n */\n protected fieldValue?: unknown;\n\n /**\n * Whether the value is nullable\n * If set to false and value is null, it will be returned as undefined\n */\n protected isNullable = false;\n\n /**\n * Whether this field is an array\n * When true, transform() maps over each element using the base type\n */\n protected isArrayField = false;\n\n /**\n * Default value\n */\n protected defaultValue?: unknown;\n\n /**\n * Date format\n */\n protected dateFormat = \"DD-MM-YYYY hh:mm:ss A\";\n\n /**\n * Input key\n */\n protected inputKeyToUse?: string;\n\n /**\n * Add a condition before transforming the value\n */\n protected condition?: () => boolean;\n\n /**\n * Define how date fields are returned\n * If type of the date options is string then it will be returned as a string\n * otherwise it will be returned as an object contains the date options\n */\n protected dateOptionsInput: ResourceFieldBuilderDateOutputOptions = {\n format: true,\n timestamp: true,\n timezone: false,\n locale: false,\n offset: false,\n humanTime: true,\n iso: true,\n };\n\n /**\n * Constructor\n */\n public constructor(protected readonly type: ResourceOutputValueCastType) {\n //\n }\n\n /**\n * Parse a cast type string (including suffixes) into a configured builder.\n * Suffix order: [] before ? (e.g. \"string[]?\")\n * Parsing strips right-to-left: ? first, then [].\n */\n public static fromCastType(castType: string): ResourceFieldBuilder {\n let baseType = castType;\n let nullable = false;\n let isArray = false;\n\n if (baseType.endsWith(\"?\")) {\n nullable = true;\n baseType = baseType.slice(0, -1);\n }\n\n if (baseType.endsWith(\"[]\")) {\n isArray = true;\n baseType = baseType.slice(0, -2);\n }\n\n const builder = new ResourceFieldBuilder(baseType as ResourceOutputValueCastType);\n if (nullable) builder.nullable();\n if (isArray) builder.array();\n return builder;\n }\n\n /**\n * Set input key\n * Will be used in transformation if provided\n */\n public setInputKey(key: string) {\n this.inputKeyToUse = key;\n\n return this;\n }\n\n /**\n * Add a condition before transforming the value\n */\n public when(condition: () => boolean) {\n this.condition = condition;\n return this;\n }\n\n /**\n * Set whether the value is nullable\n */\n public nullable() {\n this.isNullable = true;\n return this;\n }\n\n /**\n * Mark this field as an array\n * transform() will map over each element using the base type\n */\n public array() {\n this.isArrayField = true;\n return this;\n }\n\n /**\n * Get input key\n */\n public getInputKey() {\n return this.inputKeyToUse;\n }\n\n /**\n * Set default value\n */\n public default(value: unknown) {\n this.defaultValue = value;\n\n return this;\n }\n\n /**\n * Set field format\n */\n public format(format: string) {\n this.dateFormat = format;\n\n return this;\n }\n\n /**\n * Set date options\n * This will override current date options\n */\n public dateOptions(options: ResourceFieldBuilderDateOutputOptions) {\n this.dateOptionsInput = options;\n\n return this;\n }\n\n /**\n * Transform the value.\n * When isArrayField is true, maps over each element using transformSingleValue.\n */\n public transform(value: any, locale?: string) {\n if (this.isArrayField) {\n if (!Array.isArray(value)) {\n return this.isNullable ? null : [];\n }\n\n return value\n .map((item) => this.transformSingleValue(item, locale))\n .filter((v) => v !== undefined);\n }\n\n return this.transformSingleValue(value, locale);\n }\n\n /**\n * Transform a single value according to the base type.\n */\n protected transformSingleValue(value: any, locale?: string) {\n if (value === undefined || value === null) {\n return this.isNullable ? null : this.defaultValue;\n }\n\n if (this.condition && !this.condition()) {\n return this.isNullable ? null : this.defaultValue;\n }\n\n switch (this.type) {\n case \"string\":\n return typeof value?.toHexString === \"function\" ? value.toHexString() : String(value);\n case \"number\": {\n const num = Number(value);\n return isNaN(num) ? (this.isNullable ? null : undefined) : num;\n }\n case \"boolean\":\n return Boolean(value);\n case \"float\": {\n const float = parseFloat(value);\n return isNaN(float) ? (this.isNullable ? null : undefined) : float;\n }\n\n case \"int\": {\n const int = parseInt(value);\n return isNaN(int) ? (this.isNullable ? null : undefined) : int;\n }\n\n case \"date\":\n return this.transformDate(value as string | Date, locale);\n case \"localized\":\n return this.transformLocalized(value as LocalizedObject[], locale);\n case \"url\":\n return url(value as string);\n case \"uploadsUrl\":\n return uploadsUrl(value as string);\n case \"storageUrl\":\n return storage.url(value as string);\n case \"object\":\n return isObject(value) && !Array.isArray(value) && Object.keys(value).length > 0\n ? value\n : this.isNullable\n ? null\n : undefined;\n case \"array\":\n return Array.isArray(value) ? value : this.isNullable ? null : undefined;\n }\n }\n\n /**\n * Transform date value\n */\n protected transformDate(value: string | Date, locale?: string) {\n // Bad data (\"\" or garbage) must not throw and turn the response into a 500\n if (!dayjs((value as any)?.iso || value).isValid()) {\n return this.isNullable ? null : undefined;\n }\n\n if (typeof this.dateOptionsInput === \"string\") {\n if (this.dateOptionsInput === \"format\") {\n return dayjs(value).format(this.dateFormat);\n }\n\n if (this.dateOptionsInput === \"iso\") {\n return dayjs(value).toISOString();\n }\n\n if (this.dateOptionsInput === \"timestamp\") {\n return dayjs(value).valueOf();\n }\n\n if (this.dateOptionsInput === \"humanTime\") {\n return (dayjs as any)(value).fromNow();\n }\n\n if (this.dateOptionsInput === \"locale\") {\n if (!locale) {\n return dayjs(value).format(this.dateFormat);\n }\n\n return dayjs(value).locale(locale).format(this.dateFormat);\n }\n }\n\n // now manage it as an object based on date options what's marked as true\n const output: {\n format?: string;\n timestamp?: number;\n humanTime?: string;\n locale?: string;\n iso?: string;\n } = {};\n\n let dayjsObject = dayjs((value as any)?.iso || value);\n\n if (locale) {\n dayjsObject = dayjsObject.locale(locale);\n }\n\n if (this.dateOptionsInput.iso) {\n output.iso = dayjsObject.toISOString();\n }\n\n if (this.dateOptionsInput.format) {\n output.format = dayjsObject.format(this.dateFormat);\n }\n\n if (this.dateOptionsInput.timestamp) {\n output.timestamp = dayjsObject.valueOf();\n }\n\n if (this.dateOptionsInput.humanTime) {\n output.humanTime = (dayjsObject as any).fromNow();\n }\n\n if (this.dateOptionsInput.locale) {\n output.locale = dayjsObject.format(this.dateFormat);\n }\n\n if (this.dateOptionsInput.iso) {\n output.iso = dayjsObject.toISOString();\n }\n\n return output;\n }\n\n /**\n * Transform localized value\n */\n protected transformLocalized(value: LocalizedObject[] | string, locale?: string) {\n if (typeof value === \"string\") {\n return value;\n }\n\n if (!locale) {\n return value[0]?.value || value;\n }\n\n return value.find((item) => item.localeCode === locale)?.value;\n }\n}\n"],"mapp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E,IAAI,OAAO,UAAU,UACnB,OAAO;EAGT,IAAI,CAAC,QACH,OAAO,MAAM,EAAE,EAAE,SAAS;EAG5B,OAAO,MAAM,MAAM,SAAS,KAAK,eAAe,MAAM,CAAC,EAAE;CAC3D;AACF"}
|
|
@@ -170,6 +170,11 @@ declare class Resource implements ResourceContract {
|
|
|
170
170
|
* Transform a single array item according to the given schema
|
|
171
171
|
*/
|
|
172
172
|
protected transformArrayItem(item: any, schema: Record<string, ResourceFieldConfig>, locale?: string): GenericObject;
|
|
173
|
+
/**
|
|
174
|
+
* Resolve one schema field from a model or plain object. Mongo records use `_id`
|
|
175
|
+
* internally, while resources expose `id` by convention.
|
|
176
|
+
*/
|
|
177
|
+
protected resolveSourceValue(source: GenericObject | Resource | Model, outputKey: string, inputKey?: string): any;
|
|
173
178
|
/**
|
|
174
179
|
* Get a input value for the given key
|
|
175
180
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resource.d.mts","names":[],"sources":["../../../../../../../core/src/resource/resource.ts"],"mappings":";;;;;;;;AAoBA;UAAiB,gBAAA;;;;EAIf,QAAA,EAAU,aAAA;EAeA;;;EAVV,IAAA,EAAM,aAAA;EA8BU;;;EAzBhB,YAAA,EAAc,aAAA;EAwCgB;;;EAnC9B,MAAA,IAAU,aAAA;EAuDkB;;;EAlD5B,SAAA,CAAU,KAAA,OAAY,IAAA,EAAM,2BAAA,EAA6B,MAAA;EA4Db;;;EAvD5C,GAAA,CAAI,GAAA,UAAa,YAAA;EApBX;;;EAyBN,GAAA,CAAI,GAAA,UAAa,KAAA,QAAa,gBAAA;EAfpB;;;EAoBV,OAAA,CAAQ,MAAA,EAAQ,MAAA,SAAe,mBAAA,IAAuB,mBAAA;EAfhC;;;EAoBtB,MAAA,CAAO,QAAA,YAAoB,oBAAA;EAfV;;;EAoBjB,IAAA,CAAK,QAAA,YAAoB,oBAAA;EAfK;;;EAoB9B,SAAA,CAAU,QAAA,YAAoB,oBAAA;EAftB;;;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iB,oBAAA;EAlEb;;;EAAA,UAyEL,YAAA,CAAa,IAAA,EAAM,2BAAA,EAA6B,QAAA,YAAiB,oBAAA;AAAA"}
|
|
@@ -66,8 +66,10 @@ var Resource = class Resource {
|
|
|
66
66
|
transformOutput() {
|
|
67
67
|
const localeCode = useRequestStore()?.request?.locale;
|
|
68
68
|
const parsedSchema = this.resolveParsedSchema();
|
|
69
|
+
const source = this.originalData instanceof Model ? this.originalData : this.resource;
|
|
69
70
|
for (const [outputKey, outputSettings] of Object.entries(parsedSchema)) {
|
|
70
|
-
const
|
|
71
|
+
const inputKey = outputSettings instanceof ResourceFieldBuilder ? outputSettings.getInputKey() : void 0;
|
|
72
|
+
const inputValue = this.resolveSourceValue(source, outputKey, inputKey);
|
|
71
73
|
const outputValue = this.transformValue(inputValue, outputSettings, localeCode);
|
|
72
74
|
if (outputValue !== void 0) this.set(outputKey, outputValue);
|
|
73
75
|
}
|
|
@@ -108,10 +110,8 @@ var Resource = class Resource {
|
|
|
108
110
|
outputValue = value.map((item) => new outputSettings(item).toJSON()).filter((v) => v !== void 0);
|
|
109
111
|
} else outputValue = new outputSettings(value).toJSON();
|
|
110
112
|
} else if (typeof outputSettings === "function") outputValue = outputSettings.call(this, value, this);
|
|
111
|
-
else if (outputSettings instanceof ResourceFieldBuilder)
|
|
112
|
-
|
|
113
|
-
outputValue = outputSettings.transform(inputKey ? this.get(inputKey) : value, locale);
|
|
114
|
-
} 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);
|
|
113
|
+
else if (outputSettings instanceof ResourceFieldBuilder) outputValue = outputSettings.transform(value, locale);
|
|
114
|
+
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);
|
|
115
115
|
else outputValue = this.transformArrayItem(value, outputSettings.schema, locale);
|
|
116
116
|
return outputValue;
|
|
117
117
|
}
|
|
@@ -156,13 +156,24 @@ var Resource = class Resource {
|
|
|
156
156
|
fieldKey = outputSettings[0];
|
|
157
157
|
valueTransformType = outputSettings[1];
|
|
158
158
|
}
|
|
159
|
-
const
|
|
159
|
+
const inputKey = valueTransformType instanceof ResourceFieldBuilder ? valueTransformType.getInputKey() : void 0;
|
|
160
|
+
const inputValue = this.resolveSourceValue(item, outputKey, inputKey ?? fieldKey);
|
|
160
161
|
const outputValue = this.transformValue(inputValue, valueTransformType, locale);
|
|
161
162
|
if (outputValue !== void 0) set(transformedItem, outputKey, outputValue);
|
|
162
163
|
}
|
|
163
164
|
return transformedItem;
|
|
164
165
|
}
|
|
165
166
|
/**
|
|
167
|
+
* Resolve one schema field from a model or plain object. Mongo records use `_id`
|
|
168
|
+
* internally, while resources expose `id` by convention.
|
|
169
|
+
*/
|
|
170
|
+
resolveSourceValue(source, outputKey, inputKey) {
|
|
171
|
+
const key = inputKey ?? outputKey;
|
|
172
|
+
const read = (field) => source instanceof Model ? source.get(field) : get(source, field);
|
|
173
|
+
const value = read(key);
|
|
174
|
+
return outputKey === "id" && key === "id" && value === void 0 ? read("_id") : value;
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
166
177
|
* Get a input value for the given key
|
|
167
178
|
*/
|
|
168
179
|
get(key, defaultValue) {
|
|
@@ -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 {\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(): GenericObject;\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 {\n new (originalData: GenericObject | Resource | Model): ResourceContract;\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\n for (const [outputKey, outputSettings] of Object.entries(parsedSchema)) {\n const inputValue = this.get(outputKey);\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 const inputKey = outputSettings.getInputKey();\n outputValue = outputSettings.transform(inputKey ? this.get(inputKey) : 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 inputValue = get(item, 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 * 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;kBA3DO,CAAC;cAKL,CAAC;EAuD5B,IAAI,KAAK,wBAAwB,OAC/B,KAAK,WAAW,KAAK,aAAa;OAC7B,IAAI,KAAK,wBAAwB,UACtC,KAAK,WAAW,KAAK,aAAa;OAElC,KAAK,WAAW,KAAK;CAEzB;;;;CAKA,AAAO,SAAS;EACd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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 {\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(): GenericObject;\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 {\n new (originalData: GenericObject | Resource | Model): ResourceContract;\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;kBA3DO,CAAC;cAKL,CAAC;EAuD5B,IAAI,KAAK,wBAAwB,OAC/B,KAAK,WAAW,KAAK,aAAa;OAC7B,IAAI,KAAK,wBAAwB,UACtC,KAAK,WAAW,KAAK,aAAa;OAElC,KAAK,WAAW,KAAK;CAEzB;;;;CAKA,AAAO,SAAS;EACd,KAAK,KAAK;EACV,KAAK,gBAAgB;EACrB,KAAK,OAAO;EAEZ,OAAO,KAAK;CACd;;;;;CAMA,AAAU,OAAO,CAEjB;;;;;;CAOA,AAAU,kBAAkB;EAC1B,MAAM,aAAa,gBAAgB,CAAC,EAAE,SAAS;EAC/C,M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,KAAA,CAAM,OAAA,EAAS,oBAAA,EAAsB,QAAA,EAAU,mBAAA;EAxSpD;;;EA4VK,MAAA,CAAO,MAAA,UAAgB,QAAA;EAvOL;;;;;;;;;;;;EAuPlB,OAAA,CAAQ,OAAA,mBAA0B,QAAA;EAzOkC;;;;;;EAmP9D,cAAA,UACX,UAAA,UACA,QAAA,QAAgB,CAAA,GAAI,OAAA,CAAQ,CAAA,IAC3B,OAAA,CAAQ,CAAA;EA/O2C;;;;;EAgR/C,wBAAA,CAAyB,UAAA;EAzQoC;;;;;;;;EAmSvD,0BAAA,IACX,WAAA,EAAa,QAAA,UACb,OAAA,QAAe,CAAA,GAAI,OAAA,CAAQ,CAAA,IAC1B,OAAA,CAAQ,CAAA;EAxRwB;;;EAAA,QAsU3B,gBAAA;EA/TD;;;EA2YA,IAAA,IAAI,KAAA;EA3YwD;;;;;;EAqZ5D,iBAAA,aAA8B,aAAA;EAhY9B;;;;;;;;EAgZA,UAAA;EA1YH;;;EAiZG,IAAA,CAAK,MAAA,EAAQ,eAAA;EAjZyB;;;;EA0ctC,aAAA,CAAc,MAAA,EAAQ,eAAA;EAnWP;;;EAmff,QAAA,CAAS,IAAA,UAAc,MAAA,GAAQ,MAAA;EA/b/B;;;EAAA,QAieC,WAAA;AAAA;AAAA,cA4EG,MAAA,EAAM,MAAuB"}
|
package/esm/router/router.mjs
CHANGED
|
@@ -561,6 +561,7 @@ var Router = class Router {
|
|
|
561
561
|
return routeRegistry;
|
|
562
562
|
};
|
|
563
563
|
server.addHook("onRequest", async (fastifyRequest, fastifyReply) => {
|
|
564
|
+
if (fastifyRequest.routeOptions.url !== "*") return;
|
|
564
565
|
const match = resolveRouteRegistry().find(fastifyRequest.method, fastifyRequest.url);
|
|
565
566
|
if (!match) return;
|
|
566
567
|
fastifyRequest.matchedDevRoute = match;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"router.mjs","names":[],"sources":["../../../../../../../core/src/router/router.ts"],"sourcesContent":["import proxy, { type FastifyHttpProxyOptions } from \"@fastify/http-proxy\";\nimport fastifyStatic, { type FastifyStaticOptions } from \"@fastify/static\";\nimport { ltrim, merge, toCamelCase, trim } from \"@mongez/reinforcements\";\nimport { isEmpty } from \"@mongez/supportive-is\";\nimport { log } from \"@warlock.js/logger\";\nimport type { FastifyReply, FastifyRequest } from \"fastify\";\nimport { container } from \"../container\";\nimport { buildCorsOptions } from \"../http/build-cors-options\";\nimport { Request } from \"../http/request\";\nimport { Response } from \"../http/response\";\nimport { type FastifyInstance } from \"../http/server\";\nimport { buildTracingContext, dispatchPhase, isTracingEnabled } from \"../http/tracing\";\nimport { describeRouteForLog } from \"./describe-route-for-log\";\nimport { logRequestLifecycle } from \"./log-request-lifecycle\";\nimport {\n forgetPositionalHandlerSuspects,\n inspectHandlerSignature,\n reportPositionalHandlerSuspects,\n} from \"./positional-handler-diagnostics\";\nimport { normalizeRoutePath } from \"./normalize-route-path\";\nimport { RouteBuilder } from \"./route-builder\";\nimport { buildRouteRateLimit } from \"./build-route-rate-limit\";\nimport { DEV_DISPATCH_METHODS, buildNotFoundBody, createDevRateLimiter } from \"./dev-dispatch\";\nimport { RouteRegistry } from \"./route-registry\";\nimport { routeNameMethodSuffix } from \"./route-name-method-suffix\";\nimport type {\n GroupedRoutesOptions,\n HttpContext,\n NamedApiRoute,\n RequestHandler,\n RequestHandlerType,\n RequestHandlerValidation,\n ResourceMethod,\n Route,\n RouteOptions,\n RouteResource,\n RouterGroupCallback,\n RouterStacks,\n} from \"./types\";\n\n/**\n * A Fastify lifecycle hook as it may be declared in a route's `serverOptions`.\n * Fastify accepts a single hook or an array in either position.\n */\ntype RouteLifecycleHook = (\n request: FastifyRequest,\n reply: FastifyReply,\n) => unknown | Promise<unknown>;\n\n/**\n * The pre-handler phases the dev server forwards from a route's `serverOptions`.\n *\n * These are the admission-control phases and they share the `(request, reply)`\n * signature. `preParsing` is deliberately absent — it must return the payload\n * stream, so forwarding it generically would corrupt the body rather than\n * guard it. `bodyLimit` cannot be forwarded at all; Fastify reads it at\n * registration time and no hook can bound a body already being parsed.\n */\nconst FORWARDED_ROUTE_PHASES = [\"onRequest\", \"preValidation\", \"preHandler\"] as const;\n\ntype ForwardedRoutePhase = (typeof FORWARDED_ROUTE_PHASES)[number];\n\n/**\n * The route the dev dispatcher matched, stashed on the request so the hooks and\n * the wildcard handler all act on one match rather than each matching again.\n */\ntype DevMatchedRoute = { route: Route; params: Record<string, string> };\n\ntype DevDispatchRequest = FastifyRequest & {\n matchedDevRoute?: DevMatchedRoute;\n};\n\nfunction toHookList(\n hook: RouteLifecycleHook | RouteLifecycleHook[] | undefined,\n): RouteLifecycleHook[] {\n if (!hook) {\n return [];\n }\n\n return Array.isArray(hook) ? hook : [hook];\n}\n\n/**\n * Run a matched route's hooks for one phase.\n *\n * Returning the reply is how an async Fastify hook signals that it has answered\n * the request; the chain must stop there, so the value is propagated rather\n * than discarded.\n */\nasync function runRouteHooks(\n route: Route,\n phase: ForwardedRoutePhase,\n request: FastifyRequest,\n reply: FastifyReply,\n) {\n const hooks = toHookList(\n route.serverOptions?.[phase] as RouteLifecycleHook | RouteLifecycleHook[] | undefined,\n );\n\n for (const hook of hooks) {\n const outcome = await hook(request, reply);\n\n if (outcome === reply) {\n return reply;\n }\n }\n\n return undefined;\n}\n\n/**\n * Describe one claimant of a route name, for the duplicate-name error.\n *\n * `warlock dev` registers SSR page routes on the same router as API routes, so\n * the two share a single route-name namespace and collide across kinds. The\n * error is only actionable if it says which claimant is which, so `isPage` —\n * the router's only route-kind discriminator — is what separates them here.\n *\n * `sourceFile` is stamped only on routes registered through `withSourceFile`.\n * Routes registered without that scope have no owner, so say the source is\n * unknown rather than printing an empty string.\n */\nfunction describeRouteClaimant(route: Route) {\n const type = route.isPage ? \"page route\" : \"API route\";\n const source = route.sourceFile ? `declared in ${route.sourceFile}` : \"source file unknown\";\n\n return `${type} ${route.method} ${route.path} (${source})`;\n}\n\nexport class Router {\n /**\n * Routes list\n */\n private routes: Route[] = [];\n\n /**\n * Bumped on every mutation of {@link routes}.\n *\n * The dev dispatcher caches a route registry and needs to know when it is\n * stale. Comparing `routes.length` would miss an HMR reload that replaces a\n * route without changing the count — the registry would then keep matching\n * paths that no longer exist. A version counter cannot miss that.\n */\n private routesVersion = 0;\n\n /**\n * In-progress atomic replacement, when one exists. Reads continue to use\n * {@link routes}; mutations and collision checks use this isolated draft.\n */\n private routeReplacementTransaction?: {\n routes: Route[];\n removedSourceFiles: Set<string>;\n addedRoutes: Route[];\n };\n\n /**\n * Router Instance\n */\n private static instance: Router;\n\n /**\n * Static paths\n */\n protected staticDirectories: FastifyStaticOptions[] = [];\n\n /**\n * Event listeners\n */\n protected eventListeners: Record<string, ((router: Router, server: FastifyInstance) => void)[]> =\n {};\n\n /**\n * Stacks\n * Stacks will be used for grouping routes to add prefix, name or middleware\n */\n protected stacks: RouterStacks = {\n prefix: [],\n name: [],\n middleware: [],\n };\n\n /**\n * Get router instance\n */\n public static getInstance() {\n if (!Router.instance) {\n Router.instance = new Router();\n }\n\n return Router.instance;\n }\n\n private constructor() {\n //\n }\n\n /**\n * Listen to router before scan\n */\n public beforeScanning(callback: (router: Router, server: FastifyInstance) => void) {\n this.eventListeners.beforeScan = [...(this.eventListeners.beforeScan || []), callback];\n\n return this;\n }\n\n /**\n * Listen to router after scanning\n */\n public afterScanning(callback: (router: Router, server: FastifyInstance) => void) {\n this.eventListeners.afterScanning = [...(this.eventListeners.afterScanning || []), callback];\n\n return this;\n }\n\n /**\n * Redirect path to another path\n */\n public redirect(from: string, to: string, redirectMode: \"temporary\" | \"permanent\" = \"temporary\") {\n return this.get(from, ({ response }) => {\n response.redirect(to, redirectMode === \"temporary\" ? 302 : 301);\n });\n }\n\n /**\n * Server static folder\n */\n public directory(options: FastifyStaticOptions) {\n this.staticDirectories.push(options);\n\n return this;\n }\n\n /**\n * Serve file\n */\n public file(path: string, location: string, cacheTime?: number) {\n return this.get(path, ({ response }) => {\n response.sendFile(location, cacheTime);\n });\n }\n\n /**\n * Serve cached file, it will cache the file to 1 year by default\n */\n public cachedFile(path: string, location: string, cacheTime?: number) {\n return this.get(path, ({ response }) => {\n response.sendCachedFile(location, cacheTime);\n });\n }\n\n /**\n * Serve list of files\n */\n public files(files: Record<string, string>, cacheTime?: number) {\n for (const [path, location] of Object.entries(files)) {\n this.get(path, ({ response }) => {\n response.sendFile(location, cacheTime);\n });\n }\n }\n\n /**\n * Serve list of cached files, it will cache the file to 1 year by default\n */\n public cachedFiles(files: Record<string, string>, cacheTime?: number) {\n for (const [path, location] of Object.entries(files)) {\n this.get(path, ({ response }) => {\n response.sendCachedFile(location, cacheTime);\n });\n }\n }\n\n /**\n * Add proxy route\n */\n public proxy(\n path: string,\n baseUrl: string,\n options?: Omit<FastifyHttpProxyOptions, \"prefix\" | \"upstream\">,\n ): this;\n public proxy(options: FastifyHttpProxyOptions): this;\n public proxy(...args: any[]) {\n this.beforeScanning((_router, server) => {\n if (args.length === 1) {\n server.register(proxy, args[0]);\n } else {\n server.register(proxy, {\n prefix: args[0],\n upstream: args[1],\n ...args[2],\n });\n }\n });\n\n return this;\n }\n\n /**\n * Add route to routes list\n */\n public add(\n method: Route[\"method\"],\n path: string | string[],\n handler: RequestHandlerType,\n options: RouteOptions = {},\n ) {\n if (Array.isArray(path)) {\n path.forEach((p) => this.add(method, p, handler, options));\n return this;\n }\n\n const prefix = this.stacks.prefix.reduce((path, prefix) => {\n return normalizeRoutePath(path, prefix);\n }, \"\");\n\n const name = this.stacks.name.reduceRight(\n (name, prefixName) => {\n return trim(prefixName + \".\" + name, \".\");\n },\n options.name || trim(path.replace(/\\//g, \".\"), \".\"),\n );\n\n // The one place a route path becomes canonical. `normalizeRoutePath` is\n // exported so the build-time page-route manifest can produce the very same\n // string without registering anything.\n path = normalizeRoutePath(prefix, path);\n\n const middlewarePrecedence = options.middlewarePrecedence || \"after\";\n\n // Work on a copy: the caller may reuse one options object for several\n // routes, and merging the group stack into it would compound per route.\n options = { ...options };\n\n if (middlewarePrecedence === \"before\") {\n options.middleware = [...(options.middleware || []), ...this.stacks.middleware];\n } else {\n options.middleware = [...this.stacks.middleware, ...(options.middleware || [])];\n }\n\n if (Array.isArray(handler)) {\n const [controller, action] = handler;\n\n if (typeof controller[action] !== \"function\") {\n throw new Error(\n `Invalid controller action \"${action}\" for controller \"${controller.constructor.name}\"`,\n );\n }\n\n handler = controller[action].bind(controller) as RequestHandler;\n\n if (!handler.validation) {\n handler.validation = {};\n if (controller[`${action}ValidationSchema`]) {\n handler.validation.schema = controller[`${action}ValidationSchema`]();\n }\n\n if (controller[`${action}Validate`]) {\n handler.validation.validate = controller[`${action}Validate`];\n }\n }\n }\n\n const routeData: Route = {\n method,\n path,\n handler,\n ...options,\n name,\n rateLimit: options.rateLimit,\n $prefix: prefix || \"/\",\n // it must be a new array to avoid modifying the original array\n $prefixStack: [...this.stacks.prefix],\n // Inject source file from stacks if set\n sourceFile: this.stacks.sourceFile || \"\",\n };\n\n const routes = this.routeReplacementTransaction?.routes ?? this.routes;\n\n if (routeData.name) {\n // check if the name exists\n const route = routes.find((route) => route.name === routeData.name);\n\n if (route) {\n // check again if the route name exists with the same method\n if (route.method === routeData.method) {\n throw new Error(\n `Route name \"${routeData.name}\" is already taken.\\n` +\n ` already registered: ${describeRouteClaimant(route)}\\n` +\n ` now being added: ${describeRouteClaimant(routeData)}\\n` +\n `Pages and API routes share one route-name namespace, so a name can only be ` +\n `claimed once. Rename one of them via the \"name\" route option.`,\n );\n } else {\n routeData.name += routeNameMethodSuffix(routeData.method);\n }\n }\n }\n\n // Registration-time only — nothing here runs per request. Suspects are\n // collected now and reported together at boot (see `scan`), so a route file\n // written against v4 produces one legible list instead of a mystery 500 per\n // request. Recorded after the collision check so a route that never lands\n // is never reported.\n if (this.routeReplacementTransaction) {\n this.routeReplacementTransaction.addedRoutes.push(routeData);\n } else {\n inspectHandlerSignature(routeData.handler, routeData);\n }\n\n routes.push(routeData);\n\n if (!this.routeReplacementTransaction) {\n this.routesVersion++;\n }\n\n return this;\n }\n\n /**\n * Add a request that accepts all methods\n */\n public any(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"all\" as Route[\"method\"], path, handler, options);\n }\n\n /**\n * Add get request method\n */\n public get(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"GET\", path, handler, options);\n }\n\n /**\n * Add post request method\n */\n public post(path: string | string[], handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"POST\", path, handler, options);\n }\n\n /**\n * Add put request method\n */\n public put(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"PUT\", path, handler, options);\n }\n\n /**\n * Add delete request method\n */\n public delete(path: string | string[], handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"DELETE\", path, handler, options);\n }\n\n /**\n * Add patch request method\n */\n public patch(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"PATCH\", path, handler, options);\n }\n\n /**\n * Add head request method\n */\n public head(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"HEAD\", path, handler, options);\n }\n\n /**\n * Add options request method\n */\n public options(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"OPTIONS\", path, handler, options);\n }\n\n /**\n * Get a chainable route builder for the same route path\n */\n public route(path: string, options: RouteOptions = {}) {\n return new RouteBuilder(this, path, options);\n }\n\n /**\n * Add full restful resource routes\n * This method will generate the following routes:\n * 1. GET /path: list all resources\n * 2. GET /path/:id: get a single resource\n * 3. POST /path: create a new resource\n * 4. PUT /path/:id: update a resource\n * 5. DELETE /path/:id: delete a resource\n * 6. PATCH /path/:id: update a resource partially\n */\n public restfulResource(\n path: string,\n resource: RouteResource,\n options: RouteOptions & {\n only?: ResourceMethod[];\n except?: ResourceMethod[];\n replace?: Partial<Record<ResourceMethod, RequestHandler>> & {\n bulkDelete?: RequestHandler;\n };\n } = {},\n ) {\n // Derive the base resource name from the path before the group below\n // clears it for use as the routes' relative path. `options.name`, when\n // given, replaces the path-derived name entirely (see the explicit\n // `name` passed to `group()`) rather than composing with it.\n const baseResourceName = options.name || toCamelCase(ltrim(path, \"/\"));\n\n return this.group({ prefix: path, name: baseResourceName }, () => {\n const path = \"\";\n\n // clone the resource so we don't mess up with it\n const routeResource = resource;\n\n const isAcceptableResource = (type: ResourceMethod) => {\n return Boolean(\n // check if the route is not excluded\n (!options.except || !options.except.includes(type)) &&\n // check if the only option is set and the route is included\n (!options.only || options.only.includes(type)),\n );\n };\n\n if (routeResource.list && isAcceptableResource(\"list\")) {\n this.get(path, options.replace?.list || routeResource.list.bind(routeResource), {\n ...options,\n name: \"list\",\n restful: true,\n });\n }\n\n if (routeResource.get && isAcceptableResource(\"get\")) {\n this.get(path + \"/:id\", options.replace?.get || routeResource.get.bind(routeResource), {\n ...options,\n name: \"single\",\n restful: true,\n });\n }\n\n if (routeResource.create && isAcceptableResource(\"create\")) {\n const handler = options.replace?.create || this.manageValidation(routeResource, \"create\");\n\n this.post(path, handler, {\n ...options,\n name: \"create\",\n restful: true,\n });\n }\n\n if (routeResource.update && isAcceptableResource(\"update\")) {\n const handler = options.replace?.update || this.manageValidation(routeResource, \"update\");\n\n this.put(path + \"/:id\", handler, {\n ...options,\n name: \"update\",\n restful: true,\n });\n }\n\n if (routeResource.patch && isAcceptableResource(\"patch\")) {\n const handler = options.replace?.patch || this.manageValidation(routeResource, \"patch\");\n\n this.patch(path + \"/:id\", handler, {\n ...options,\n name: \"patch\",\n restful: true,\n });\n }\n\n if (routeResource.delete && isAcceptableResource(\"delete\")) {\n this.delete(\n path + \"/:id\",\n options.replace?.delete || routeResource.delete.bind(routeResource),\n {\n ...options,\n name: \"delete\",\n restful: true,\n },\n );\n }\n\n if (routeResource.bulkDelete && isAcceptableResource(\"delete\")) {\n this.delete(\n path,\n options.replace?.bulkDelete || routeResource.bulkDelete.bind(routeResource),\n {\n ...options,\n name: \"bulkDelete\",\n restful: true,\n },\n );\n }\n\n return this;\n });\n }\n\n /**\n * Group routes with options\n */\n public group(options: GroupedRoutesOptions, callback: RouterGroupCallback) {\n const {\n prefix,\n // name must always be defined because\n // if there are multiple groups without name\n // they might generate the same route name\n // thus causing an error\n // in this case we need always to make sure that\n // the name is always defined.\n name = prefix ? trim(prefix.replace(/\\//g, \".\"), \".\") : undefined,\n middleware,\n } = options;\n\n if (prefix) {\n this.stacks.prefix.push(prefix);\n }\n\n if (name) {\n this.stacks.name.push(name);\n }\n\n if (middleware) {\n this.stacks.middleware.push(...middleware);\n }\n\n try {\n callback();\n } finally {\n // Always pop/splice this group's stacks, even if the callback throws,\n // so a throwing group never leaks state onto the process-global singleton.\n if (prefix) {\n this.stacks.prefix.pop();\n }\n\n if (name) {\n this.stacks.name.pop();\n }\n\n if (middleware) {\n this.stacks.middleware.splice(\n this.stacks.middleware.length - middleware.length,\n middleware.length,\n );\n }\n }\n\n return this;\n }\n\n /**\n * Add prefix to all routes in the given callback\n */\n public prefix(prefix: string, callback: () => void) {\n return this.group({ prefix }, callback);\n }\n\n /**\n * Add API version prefix to all routes in the given callback\n * Automatically formats the version as /v{version}\n * @example\n * router.version(\"1\", () => {\n * router.get(\"/users\", getUsersV1); // /v1/users\n * });\n *\n * router.version(\"2\", () => {\n * router.get(\"/users\", getUsersV2); // /v2/users\n * });\n */\n public version(version: string | number, callback: () => void) {\n return this.prefix(`/v${version}`, callback);\n }\n\n /**\n * Wrap route additions with a source file path\n * Used for tracking which routes come from which file (for HMR)\n * @param sourceFile Relative path to the source file (e.g., \"src/app/users/routes.ts\")\n * @param callback Function that adds routes (will have sourceFile injected)\n */\n public async withSourceFile<T = any>(\n sourceFile: string,\n callback: () => T | Promise<T>,\n ): Promise<T | undefined> {\n // Set source file in stacks\n this.stacks.sourceFile = sourceFile;\n\n try {\n // Execute callback (routes added here will have sourceFile injected)\n return await callback();\n } catch (error) {\n // Log loudly, then RETHROW. Swallowing here silently dropped a whole\n // route file (duplicate name, invalid action, import error) so the\n // surface 404'd with no boot error. The caller decides what a throw\n // means: at boot it aborts the boot, during HMR the dev server's\n // batch-reload handler catches it, prints it, and keeps serving.\n log.error({\n module: \"router\",\n action: \"registerRoutes\",\n message: `Failed to register routes from \"${sourceFile}\"`,\n context: { sourceFile, error },\n });\n\n throw error;\n } finally {\n // Always clear source file from stacks so a throwing file never leaks\n // its sourceFile onto the process-global singleton.\n delete this.stacks.sourceFile;\n }\n }\n\n /**\n * Remove all routes that belong to a specific source file\n * Used when reloading routes files via HMR\n * @param sourceFile Relative path to the source file\n */\n public removeRoutesBySourceFile(sourceFile: string): void {\n if (this.routeReplacementTransaction) {\n this.routeReplacementTransaction.routes = this.routeReplacementTransaction.routes.filter(\n (route) => route.sourceFile !== sourceFile,\n );\n this.routeReplacementTransaction.removedSourceFiles.add(sourceFile);\n return;\n }\n\n this.routes = this.routes.filter((route) => route.sourceFile !== sourceFile);\n\n // Keep the signature diagnostics in step, so a reload that fixes a handler\n // stops reporting the version it replaced.\n forgetPositionalHandlerSuspects(sourceFile);\n\n this.routesVersion++;\n }\n\n /**\n * Atomically replace every route owned by the given exact source-file keys.\n *\n * The installer mutates an isolated draft. Public reads keep seeing the old\n * live table across awaits, and a failed installer discards every draft\n * mutation. A successful installer swaps the whole draft in one synchronous\n * commit and invalidates the dev route registry exactly once.\n */\n public async replaceRoutesBySourceFiles<T>(\n sourceFiles: Iterable<string>,\n install: () => T | Promise<T>,\n ): Promise<T> {\n if (this.routeReplacementTransaction) {\n throw new Error(\"Cannot nest route replacement transactions\");\n }\n\n const removedSourceFiles = new Set(sourceFiles);\n\n this.routeReplacementTransaction = {\n routes: this.routes.filter((route) => !removedSourceFiles.has(route.sourceFile)),\n removedSourceFiles,\n addedRoutes: [],\n };\n\n try {\n const result = await install();\n const transaction = this.routeReplacementTransaction!;\n\n this.routes = transaction.routes;\n this.routeReplacementTransaction = undefined;\n\n // Diagnostic state follows the same commit boundary as the route table.\n // Added routes were deliberately not inspected while still speculative.\n for (const sourceFile of transaction.removedSourceFiles) {\n forgetPositionalHandlerSuspects(sourceFile);\n }\n\n const committedRoutes = new Set(transaction.routes);\n\n for (const route of transaction.addedRoutes) {\n if (committedRoutes.has(route)) {\n inspectHandlerSignature(route.handler, route);\n }\n }\n\n this.routesVersion++;\n\n return result;\n } catch (error) {\n this.routeReplacementTransaction = undefined;\n throw error;\n }\n }\n\n /**\n * Manage validation system for the given resource\n */\n private manageValidation(resource: RouteResource, method: \"create\" | \"update\" | \"patch\") {\n const handler = resource[method]?.bind(resource) as RequestHandler;\n\n const methodValidation = resource?.validation?.[method];\n\n if (method === \"patch\") {\n handler.validation = methodValidation;\n\n if (handler.validation?.validate) {\n handler.validation.validate = handler.validation.validate.bind(resource);\n }\n\n if (resource.validation?.patch) {\n handler.validation = merge(resource.validation.patch, handler.validation);\n }\n\n return handler;\n }\n\n if (!resource.validation || (!methodValidation && !resource.validation.all)) return handler;\n\n if (resource.validation.all) {\n const validationMethods = {\n all: resource?.validation?.all?.validate,\n [method]: methodValidation?.validate,\n };\n\n const validation: RequestHandlerValidation = {};\n\n if (resource.validation.all.schema || methodValidation?.schema) {\n if (!methodValidation?.schema && resource.validation.all.schema) {\n // Case 2: Only all.schema exists - clone it for this method\n validation.schema = resource.validation.all.schema;\n } else if (methodValidation?.schema && resource.validation.all.schema) {\n // Case 3: Both exist - merge them (all is base, method overrides)\n validation.schema = resource.validation.all.schema.merge(methodValidation.schema);\n } else if (methodValidation?.schema && !resource.validation.all.schema) {\n // Case 1: Only method schema exists - use it directly\n validation.schema = methodValidation.schema;\n }\n // Case 4: Neither exists - handled by outer if being false\n }\n\n if (validationMethods.all || validationMethods[method]) {\n validation.validate = async ({ request, response }: HttpContext) => {\n if (validationMethods.all) {\n const output = await validationMethods.all.call(resource, { request, response });\n\n if (output) return output;\n }\n\n if (validationMethods[method]) {\n return await validationMethods[method]?.call(resource, { request, response });\n }\n\n return;\n };\n }\n\n if (!isEmpty(validation)) {\n handler.validation = validation;\n }\n } else {\n handler.validation = resource.validation[method];\n\n if (handler.validation?.validate) {\n handler.validation.validate = handler.validation.validate.bind(resource);\n }\n }\n\n return handler;\n }\n\n /**\n * Get all routes list\n */\n public list() {\n return this.routes;\n }\n\n /**\n * Return fresh browser-safe snapshots of named, non-page routes.\n *\n * Names are the registered names, including method suffixes. `all` stays\n * intact as route metadata; consumers decide whether their use supports it.\n */\n public getNamedApiRoutes(): readonly NamedApiRoute[] {\n return Object.freeze(\n this.routes\n .filter((route) => !route.isPage && typeof route.name === \"string\" && route.name.length > 0)\n .map((route) => Object.freeze({ name: route.name!, path: route.path, method: route.method })),\n );\n }\n\n /**\n * Number of routes currently registered on the singleton.\n *\n * Used as a readiness signal: a successful boot that ends up with zero\n * routes almost always means a route module failed to register silently\n * (see `withSourceFile`), so callers can surface that instead of letting\n * the whole surface 404.\n */\n public routeCount(): number {\n return this.routes.length;\n }\n\n /**\n * Register routes to the server\n */\n public scan(server: FastifyInstance) {\n // Every route is registered by the time we scan, so this is the first\n // moment the whole list can be reported at once — and it is still before a\n // single request is served.\n reportPositionalHandlerSuspects();\n\n this.eventListeners.beforeScan?.forEach((callback) => callback(this, server));\n\n // Fastify automatically exposes HEAD for every GET route. When an app\n // declares its own HEAD route at the same path, suppress only that GET\n // route's implicit registration so the explicit handler owns HEAD,\n // regardless of declaration order.\n const explicitHeadPaths = new Set(\n this.routes\n .filter((route) => route.method.toLowerCase() === \"head\")\n .map((route) => route.path),\n );\n\n this.routes.forEach((route) => {\n const requestMethod = route.method.toLowerCase();\n const requestMethodFunction = server[requestMethod].bind(server);\n\n const options = {\n ...route.serverOptions,\n ...(requestMethod === \"get\" &&\n explicitHeadPaths.has(route.path) && { exposeHeadRoute: false }),\n config: {\n ...route.serverOptions?.config,\n ...(route.rateLimit && { rateLimit: buildRouteRateLimit(route.rateLimit) }),\n },\n };\n\n requestMethodFunction(\n route.path,\n options,\n async (baseRequest: FastifyRequest, reply: FastifyReply) => {\n const { output, response } = await this.handleRoute(route)(baseRequest, reply);\n\n return output || response.baseResponse;\n },\n );\n });\n\n for (const directoryOptions of this.staticDirectories) {\n server.register(fastifyStatic, {\n ...directoryOptions,\n decorateReply: false,\n });\n }\n\n this.eventListeners.afterScanning?.forEach((callback) => callback(this, server));\n }\n\n /**\n * Scan routes for the development server\n * Uses wildcard routing with find-my-way for HMR support\n */\n public scanDevServer(server: FastifyInstance) {\n // Same boot-time report as production `scan`. Routes reloaded later by HMR\n // are still recorded, but only surface on the next scan or via\n // `warlock doctor`.\n reportPositionalHandlerSuspects();\n\n this.eventListeners.beforeScan?.forEach((callback) => callback(this, server));\n\n let routeRegistry: RouteRegistry | undefined;\n let registryVersion = -1;\n\n const applyDevRateLimit = createDevRateLimiter(server);\n\n // Rebuilt when the route table changes rather than per request. Building it\n // inside the handler re-registered every route on every hit — and `all`\n // routes expand into seven registrations each. Keyed on `routesVersion`\n // rather than on the route count, so an HMR reload that swaps a route\n // without changing the count still invalidates.\n const resolveRouteRegistry = () => {\n if (routeRegistry && registryVersion === this.routesVersion) {\n return routeRegistry;\n }\n\n routeRegistry = new RouteRegistry();\n\n routeRegistry.register(this.routes);\n\n registryVersion = this.routesVersion;\n\n return routeRegistry;\n };\n\n // Matching happens here, in Fastify's own onRequest phase, so a route's\n // `serverOptions.onRequest` still runs BEFORE body parsing. Production\n // `scan()` gets that from per-route registration; the wildcard dispatcher\n // has no per-route slot, so without this the hook silently never runs.\n server.addHook(\n \"onRequest\",\n async (fastifyRequest: FastifyRequest, fastifyReply: FastifyReply) => {\n const match = resolveRouteRegistry().find(fastifyRequest.method, fastifyRequest.url);\n\n if (!match) {\n return undefined;\n }\n\n (fastifyRequest as DevDispatchRequest).matchedDevRoute = match;\n\n fastifyRequest.params = match.params;\n\n // Same slot production gives it: the limiter runs first in onRequest,\n // ahead of the route's own hooks.\n await applyDevRateLimit(match.route, fastifyRequest, fastifyReply);\n\n if (fastifyReply.sent) {\n return fastifyReply;\n }\n\n return runRouteHooks(match.route, \"onRequest\", fastifyRequest, fastifyReply);\n },\n );\n\n for (const phase of FORWARDED_ROUTE_PHASES.filter((name) => name !== \"onRequest\")) {\n server.addHook(phase, async (fastifyRequest: FastifyRequest, fastifyReply: FastifyReply) => {\n const match = (fastifyRequest as DevDispatchRequest).matchedDevRoute;\n\n if (!match) {\n return undefined;\n }\n\n return runRouteHooks(match.route, phase, fastifyRequest, fastifyReply);\n });\n }\n\n // Shared handler for wildcard routing\n const wildcardHandler = async (fastifyRequest: FastifyRequest, fastifyReply: FastifyReply) => {\n const match = (fastifyRequest as DevDispatchRequest).matchedDevRoute;\n\n // No match found - return 404\n if (!match) {\n return fastifyReply\n .code(404)\n .send(buildNotFoundBody(fastifyRequest.method, fastifyRequest.url));\n }\n\n try {\n // Call the matched route handler\n const { output, response } = await this.handleRoute(match.route)(\n fastifyRequest,\n fastifyReply,\n );\n\n return output || response.baseResponse;\n } catch (error) {\n log.error(\"router\", \"dev-dispatch\", error as Error, {\n method: fastifyRequest.method,\n url: fastifyRequest.url,\n });\n\n throw error;\n }\n };\n\n // Every verb production can register. Fastify's implicit HEAD for the GET\n // wildcard is switched off so the HEAD wildcard owns it (the registry falls\n // back to the GET route, exactly as production's implicit HEAD does).\n // `@fastify/cors` registers its own OPTIONS \"*\" catch-all whenever\n // preflight is on. Plugins load after this runs, so `hasRoute` cannot see\n // it yet: decide from the same options the cors plugin receives.\n const corsOwnsPreflight = buildCorsOptions().preflight !== false;\n\n for (const method of DEV_DISPATCH_METHODS) {\n if (method === \"OPTIONS\" && (corsOwnsPreflight || server.hasRoute({ method: \"OPTIONS\", url: \"*\" }))) {\n continue;\n }\n\n server.route({\n method,\n url: \"*\",\n ...(method === \"GET\" && { exposeHeadRoute: false }),\n handler: wildcardHandler,\n });\n }\n\n // Register static directories\n for (const directoryOptions of this.staticDirectories) {\n server.register(fastifyStatic, {\n ...directoryOptions,\n decorateReply: false,\n });\n }\n\n this.eventListeners.afterScanning?.forEach((callback) => callback(this, server));\n }\n\n /**\n * Get the route path for the given route name\n */\n public getRoute(name: string, params: Record<string, any> = {}) {\n const route = this.routes.find((route) => route.name === name);\n\n if (!route) {\n throw new Error(`Route name \"${name}\" not found`);\n }\n\n const used = new Set<string>();\n\n const path = route.path.replace(/:([A-Za-z0-9_]+)(\\?)?/g, (_match, key: string, optional) => {\n const value = params[key];\n\n if (value === undefined || value === null) {\n if (optional) return \"\";\n\n throw new Error(`Route \"${name}\" is missing the \"${key}\" param`);\n }\n\n used.add(key);\n\n return encodeURIComponent(String(value));\n });\n\n const query = Object.keys(params)\n .filter((key) => !used.has(key) && params[key] !== undefined && params[key] !== null)\n .map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(String(params[key]))}`)\n .join(\"&\");\n\n return query ? `${path}?${query}` : path;\n }\n\n /**\n * Handle the given route\n */\n private handleRoute(route: Route) {\n return async (fastifyRequest: FastifyRequest, fastifyResponse: FastifyReply) => {\n const request = new Request();\n const response = new Response();\n response.setResponse(fastifyResponse);\n request.response = response;\n\n response.request = request;\n\n // \"route.match\" tracing phase: the pattern is\n // already known here (`route.path`), so this brackets the cost of\n // stamping the request/route onto the `Request` instance rather than\n // route-registry matching itself, which happens upstream of this\n // function for both the production `scan()` path and the dev wildcard\n // dispatcher (both funnel into `handleRoute`).\n const tracingEnabled = isTracingEnabled();\n const routeMatchStartedAt = tracingEnabled ? performance.now() : 0;\n\n request.setRequest(fastifyRequest).setRoute(route);\n\n if (tracingEnabled) {\n dispatchPhase(buildTracingContext(request), {\n name: \"route.match\",\n durationMs: performance.now() - routeMatchStartedAt,\n attrs: { route: route.path },\n });\n }\n\n /*\n Both ends of the entry, not just the start — see\n `log-request-lifecycle.ts`. A start line on its own made a hung request\n and an instant one look identical, and the completion line is what makes\n a MISSING one legible as a hang.\n */\n const result = await logRequestLifecycle(\n {\n info: (entry) => log.info(entry),\n warn: (entry) => log.warn(entry),\n error: (entry) => log.error(entry),\n now: () => performance.now(),\n },\n {\n module: \"route\",\n action: describeRouteForLog(route.method, route.path),\n requestId: request.id,\n context: { request, response },\n request,\n // Read after the run: the status is decided during the request.\n statusCode: () => fastifyResponse.statusCode,\n },\n () => request.execute(),\n );\n\n // A handler may return a plain object (`ReturnedResponse`). Route it\n // through `Response.send` so status, events and hooks apply, exactly as\n // middleware outputs already do.\n let output = result;\n\n if (\n output !== undefined &&\n output !== null &&\n !(output instanceof Response) &&\n (output as unknown) !== fastifyResponse\n ) {\n output = await response.send(output);\n }\n\n return {\n output,\n response,\n request,\n };\n };\n }\n}\n\nexport const router = Router.getInstance();\n\ncontainer.set(\"router\", router);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0DA,MAAM,yBAAyB;CAAC;CAAa;CAAiB;AAAY;AAc1E,SAAS,WACP,MACsB;CACtB,IAAI,CAAC,MACH,OAAO,CAAC;CAGV,OAAO,MAAM,QAAQ,IAAI,IAAI,OAAO,CAAC,IAAI;AAC3C;;;;;;;;AASA,eAAe,cACb,OACA,OACA,SACA,OACA;CACA,MAAM,QAAQ,WACZ,MAAM,gBAAgB,MACxB;CAEA,KAAK,MAAM,QAAQ,OAGjB,IAAI,MAFkB,KAAK,SAAS,KAAK,MAEzB,OACd,OAAO;AAKb;;;;;;;;;;;;;AAcA,SAAS,sBAAsB,OAAc;CAC3C,MAAM,OAAO,MAAM,SAAS,eAAe;CAC3C,MAAM,SAAS,MAAM,aAAa,eAAe,MAAM,eAAe;CAEtE,OAAO,GAAG,KAAK,GAAG,MAAM,OAAO,GAAG,MAAM,KAAK,IAAI,OAAO;AAC1D;AAEA,IAAa,SAAb,MAAa,OAAO;;;;CAuDlB,OAAc,cAAc;EAC1B,IAAI,CAAC,OAAO,UACV,OAAO,WAAW,IAAI,OAAO;EAG/B,OAAO,OAAO;CAChB;CAEA,AAAQ,cAAc;gBA3DI,CAAC;uBAUH;2BAoB8B,CAAC;wBAMrD,CAAC;gBAM8B;GAC/B,QAAQ,CAAC;GACT,MAAM,CAAC;GACP,YAAY,CAAC;EACf;CAeA;;;;CAKA,AAAO,eAAe,UAA6D;EACjF,KAAK,eAAe,aAAa,CAAC,GAAI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,MAAM,QAAQ,MAAM,IAAI;IACpD,WAAW,QAAQ;IACnB,SAAS;KAAE;KAAS;IAAS;IAC7B;IAEA,kBAAkB,gBAAgB;GACpC,SACM,QAAQ,QAAQ,CACxB;GAOA,IACE,WAAW,UACX,WAAW,QACX,EAAE,kBAAkB,aACnB,WAAuB,iBAExB,SAAS,MAAM,SAAS,KAAK,MAAM;GAGrC,OAAO;IACL;IACA;IACA;GACF;EACF;CACF;AACF;AAEA,MAAa,SAAS,OAAO,YAAY;AAEzC,UAAU,IAAI,UAAU,MAAM"}
|
|
1
|
+
{"version":3,"file":"router.mjs","names":[],"sources":["../../../../../../../core/src/router/router.ts"],"sourcesContent":["import proxy, { type FastifyHttpProxyOptions } from \"@fastify/http-proxy\";\nimport fastifyStatic, { type FastifyStaticOptions } from \"@fastify/static\";\nimport { ltrim, merge, toCamelCase, trim } from \"@mongez/reinforcements\";\nimport { isEmpty } from \"@mongez/supportive-is\";\nimport { log } from \"@warlock.js/logger\";\nimport type { FastifyReply, FastifyRequest } from \"fastify\";\nimport { container } from \"../container\";\nimport { buildCorsOptions } from \"../http/build-cors-options\";\nimport { Request } from \"../http/request\";\nimport { Response } from \"../http/response\";\nimport { type FastifyInstance } from \"../http/server\";\nimport { buildTracingContext, dispatchPhase, isTracingEnabled } from \"../http/tracing\";\nimport { describeRouteForLog } from \"./describe-route-for-log\";\nimport { logRequestLifecycle } from \"./log-request-lifecycle\";\nimport {\n forgetPositionalHandlerSuspects,\n inspectHandlerSignature,\n reportPositionalHandlerSuspects,\n} from \"./positional-handler-diagnostics\";\nimport { normalizeRoutePath } from \"./normalize-route-path\";\nimport { RouteBuilder } from \"./route-builder\";\nimport { buildRouteRateLimit } from \"./build-route-rate-limit\";\nimport { DEV_DISPATCH_METHODS, buildNotFoundBody, createDevRateLimiter } from \"./dev-dispatch\";\nimport { RouteRegistry } from \"./route-registry\";\nimport { routeNameMethodSuffix } from \"./route-name-method-suffix\";\nimport type {\n GroupedRoutesOptions,\n HttpContext,\n NamedApiRoute,\n RequestHandler,\n RequestHandlerType,\n RequestHandlerValidation,\n ResourceMethod,\n Route,\n RouteOptions,\n RouteResource,\n RouterGroupCallback,\n RouterStacks,\n} from \"./types\";\n\n/**\n * A Fastify lifecycle hook as it may be declared in a route's `serverOptions`.\n * Fastify accepts a single hook or an array in either position.\n */\ntype RouteLifecycleHook = (\n request: FastifyRequest,\n reply: FastifyReply,\n) => unknown | Promise<unknown>;\n\n/**\n * The pre-handler phases the dev server forwards from a route's `serverOptions`.\n *\n * These are the admission-control phases and they share the `(request, reply)`\n * signature. `preParsing` is deliberately absent — it must return the payload\n * stream, so forwarding it generically would corrupt the body rather than\n * guard it. `bodyLimit` cannot be forwarded at all; Fastify reads it at\n * registration time and no hook can bound a body already being parsed.\n */\nconst FORWARDED_ROUTE_PHASES = [\"onRequest\", \"preValidation\", \"preHandler\"] as const;\n\ntype ForwardedRoutePhase = (typeof FORWARDED_ROUTE_PHASES)[number];\n\n/**\n * The route the dev dispatcher matched, stashed on the request so the hooks and\n * the wildcard handler all act on one match rather than each matching again.\n */\ntype DevMatchedRoute = { route: Route; params: Record<string, string> };\n\ntype DevDispatchRequest = FastifyRequest & {\n matchedDevRoute?: DevMatchedRoute;\n};\n\nfunction toHookList(\n hook: RouteLifecycleHook | RouteLifecycleHook[] | undefined,\n): RouteLifecycleHook[] {\n if (!hook) {\n return [];\n }\n\n return Array.isArray(hook) ? hook : [hook];\n}\n\n/**\n * Run a matched route's hooks for one phase.\n *\n * Returning the reply is how an async Fastify hook signals that it has answered\n * the request; the chain must stop there, so the value is propagated rather\n * than discarded.\n */\nasync function runRouteHooks(\n route: Route,\n phase: ForwardedRoutePhase,\n request: FastifyRequest,\n reply: FastifyReply,\n) {\n const hooks = toHookList(\n route.serverOptions?.[phase] as RouteLifecycleHook | RouteLifecycleHook[] | undefined,\n );\n\n for (const hook of hooks) {\n const outcome = await hook(request, reply);\n\n if (outcome === reply) {\n return reply;\n }\n }\n\n return undefined;\n}\n\n/**\n * Describe one claimant of a route name, for the duplicate-name error.\n *\n * `warlock dev` registers SSR page routes on the same router as API routes, so\n * the two share a single route-name namespace and collide across kinds. The\n * error is only actionable if it says which claimant is which, so `isPage` —\n * the router's only route-kind discriminator — is what separates them here.\n *\n * `sourceFile` is stamped only on routes registered through `withSourceFile`.\n * Routes registered without that scope have no owner, so say the source is\n * unknown rather than printing an empty string.\n */\nfunction describeRouteClaimant(route: Route) {\n const type = route.isPage ? \"page route\" : \"API route\";\n const source = route.sourceFile ? `declared in ${route.sourceFile}` : \"source file unknown\";\n\n return `${type} ${route.method} ${route.path} (${source})`;\n}\n\nexport class Router {\n /**\n * Routes list\n */\n private routes: Route[] = [];\n\n /**\n * Bumped on every mutation of {@link routes}.\n *\n * The dev dispatcher caches a route registry and needs to know when it is\n * stale. Comparing `routes.length` would miss an HMR reload that replaces a\n * route without changing the count — the registry would then keep matching\n * paths that no longer exist. A version counter cannot miss that.\n */\n private routesVersion = 0;\n\n /**\n * In-progress atomic replacement, when one exists. Reads continue to use\n * {@link routes}; mutations and collision checks use this isolated draft.\n */\n private routeReplacementTransaction?: {\n routes: Route[];\n removedSourceFiles: Set<string>;\n addedRoutes: Route[];\n };\n\n /**\n * Router Instance\n */\n private static instance: Router;\n\n /**\n * Static paths\n */\n protected staticDirectories: FastifyStaticOptions[] = [];\n\n /**\n * Event listeners\n */\n protected eventListeners: Record<string, ((router: Router, server: FastifyInstance) => void)[]> =\n {};\n\n /**\n * Stacks\n * Stacks will be used for grouping routes to add prefix, name or middleware\n */\n protected stacks: RouterStacks = {\n prefix: [],\n name: [],\n middleware: [],\n };\n\n /**\n * Get router instance\n */\n public static getInstance() {\n if (!Router.instance) {\n Router.instance = new Router();\n }\n\n return Router.instance;\n }\n\n private constructor() {\n //\n }\n\n /**\n * Listen to router before scan\n */\n public beforeScanning(callback: (router: Router, server: FastifyInstance) => void) {\n this.eventListeners.beforeScan = [...(this.eventListeners.beforeScan || []), callback];\n\n return this;\n }\n\n /**\n * Listen to router after scanning\n */\n public afterScanning(callback: (router: Router, server: FastifyInstance) => void) {\n this.eventListeners.afterScanning = [...(this.eventListeners.afterScanning || []), callback];\n\n return this;\n }\n\n /**\n * Redirect path to another path\n */\n public redirect(from: string, to: string, redirectMode: \"temporary\" | \"permanent\" = \"temporary\") {\n return this.get(from, ({ response }) => {\n response.redirect(to, redirectMode === \"temporary\" ? 302 : 301);\n });\n }\n\n /**\n * Server static folder\n */\n public directory(options: FastifyStaticOptions) {\n this.staticDirectories.push(options);\n\n return this;\n }\n\n /**\n * Serve file\n */\n public file(path: string, location: string, cacheTime?: number) {\n return this.get(path, ({ response }) => {\n response.sendFile(location, cacheTime);\n });\n }\n\n /**\n * Serve cached file, it will cache the file to 1 year by default\n */\n public cachedFile(path: string, location: string, cacheTime?: number) {\n return this.get(path, ({ response }) => {\n response.sendCachedFile(location, cacheTime);\n });\n }\n\n /**\n * Serve list of files\n */\n public files(files: Record<string, string>, cacheTime?: number) {\n for (const [path, location] of Object.entries(files)) {\n this.get(path, ({ response }) => {\n response.sendFile(location, cacheTime);\n });\n }\n }\n\n /**\n * Serve list of cached files, it will cache the file to 1 year by default\n */\n public cachedFiles(files: Record<string, string>, cacheTime?: number) {\n for (const [path, location] of Object.entries(files)) {\n this.get(path, ({ response }) => {\n response.sendCachedFile(location, cacheTime);\n });\n }\n }\n\n /**\n * Add proxy route\n */\n public proxy(\n path: string,\n baseUrl: string,\n options?: Omit<FastifyHttpProxyOptions, \"prefix\" | \"upstream\">,\n ): this;\n public proxy(options: FastifyHttpProxyOptions): this;\n public proxy(...args: any[]) {\n this.beforeScanning((_router, server) => {\n if (args.length === 1) {\n server.register(proxy, args[0]);\n } else {\n server.register(proxy, {\n prefix: args[0],\n upstream: args[1],\n ...args[2],\n });\n }\n });\n\n return this;\n }\n\n /**\n * Add route to routes list\n */\n public add(\n method: Route[\"method\"],\n path: string | string[],\n handler: RequestHandlerType,\n options: RouteOptions = {},\n ) {\n if (Array.isArray(path)) {\n path.forEach((p) => this.add(method, p, handler, options));\n return this;\n }\n\n const prefix = this.stacks.prefix.reduce((path, prefix) => {\n return normalizeRoutePath(path, prefix);\n }, \"\");\n\n const name = this.stacks.name.reduceRight(\n (name, prefixName) => {\n return trim(prefixName + \".\" + name, \".\");\n },\n options.name || trim(path.replace(/\\//g, \".\"), \".\"),\n );\n\n // The one place a route path becomes canonical. `normalizeRoutePath` is\n // exported so the build-time page-route manifest can produce the very same\n // string without registering anything.\n path = normalizeRoutePath(prefix, path);\n\n const middlewarePrecedence = options.middlewarePrecedence || \"after\";\n\n // Work on a copy: the caller may reuse one options object for several\n // routes, and merging the group stack into it would compound per route.\n options = { ...options };\n\n if (middlewarePrecedence === \"before\") {\n options.middleware = [...(options.middleware || []), ...this.stacks.middleware];\n } else {\n options.middleware = [...this.stacks.middleware, ...(options.middleware || [])];\n }\n\n if (Array.isArray(handler)) {\n const [controller, action] = handler;\n\n if (typeof controller[action] !== \"function\") {\n throw new Error(\n `Invalid controller action \"${action}\" for controller \"${controller.constructor.name}\"`,\n );\n }\n\n handler = controller[action].bind(controller) as RequestHandler;\n\n if (!handler.validation) {\n handler.validation = {};\n if (controller[`${action}ValidationSchema`]) {\n handler.validation.schema = controller[`${action}ValidationSchema`]();\n }\n\n if (controller[`${action}Validate`]) {\n handler.validation.validate = controller[`${action}Validate`];\n }\n }\n }\n\n const routeData: Route = {\n method,\n path,\n handler,\n ...options,\n name,\n rateLimit: options.rateLimit,\n $prefix: prefix || \"/\",\n // it must be a new array to avoid modifying the original array\n $prefixStack: [...this.stacks.prefix],\n // Inject source file from stacks if set\n sourceFile: this.stacks.sourceFile || \"\",\n };\n\n const routes = this.routeReplacementTransaction?.routes ?? this.routes;\n\n if (routeData.name) {\n // check if the name exists\n const route = routes.find((route) => route.name === routeData.name);\n\n if (route) {\n // check again if the route name exists with the same method\n if (route.method === routeData.method) {\n throw new Error(\n `Route name \"${routeData.name}\" is already taken.\\n` +\n ` already registered: ${describeRouteClaimant(route)}\\n` +\n ` now being added: ${describeRouteClaimant(routeData)}\\n` +\n `Pages and API routes share one route-name namespace, so a name can only be ` +\n `claimed once. Rename one of them via the \"name\" route option.`,\n );\n } else {\n routeData.name += routeNameMethodSuffix(routeData.method);\n }\n }\n }\n\n // Registration-time only — nothing here runs per request. Suspects are\n // collected now and reported together at boot (see `scan`), so a route file\n // written against v4 produces one legible list instead of a mystery 500 per\n // request. Recorded after the collision check so a route that never lands\n // is never reported.\n if (this.routeReplacementTransaction) {\n this.routeReplacementTransaction.addedRoutes.push(routeData);\n } else {\n inspectHandlerSignature(routeData.handler, routeData);\n }\n\n routes.push(routeData);\n\n if (!this.routeReplacementTransaction) {\n this.routesVersion++;\n }\n\n return this;\n }\n\n /**\n * Add a request that accepts all methods\n */\n public any(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"all\" as Route[\"method\"], path, handler, options);\n }\n\n /**\n * Add get request method\n */\n public get(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"GET\", path, handler, options);\n }\n\n /**\n * Add post request method\n */\n public post(path: string | string[], handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"POST\", path, handler, options);\n }\n\n /**\n * Add put request method\n */\n public put(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"PUT\", path, handler, options);\n }\n\n /**\n * Add delete request method\n */\n public delete(path: string | string[], handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"DELETE\", path, handler, options);\n }\n\n /**\n * Add patch request method\n */\n public patch(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"PATCH\", path, handler, options);\n }\n\n /**\n * Add head request method\n */\n public head(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"HEAD\", path, handler, options);\n }\n\n /**\n * Add options request method\n */\n public options(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"OPTIONS\", path, handler, options);\n }\n\n /**\n * Get a chainable route builder for the same route path\n */\n public route(path: string, options: RouteOptions = {}) {\n return new RouteBuilder(this, path, options);\n }\n\n /**\n * Add full restful resource routes\n * This method will generate the following routes:\n * 1. GET /path: list all resources\n * 2. GET /path/:id: get a single resource\n * 3. POST /path: create a new resource\n * 4. PUT /path/:id: update a resource\n * 5. DELETE /path/:id: delete a resource\n * 6. PATCH /path/:id: update a resource partially\n */\n public restfulResource(\n path: string,\n resource: RouteResource,\n options: RouteOptions & {\n only?: ResourceMethod[];\n except?: ResourceMethod[];\n replace?: Partial<Record<ResourceMethod, RequestHandler>> & {\n bulkDelete?: RequestHandler;\n };\n } = {},\n ) {\n // Derive the base resource name from the path before the group below\n // clears it for use as the routes' relative path. `options.name`, when\n // given, replaces the path-derived name entirely (see the explicit\n // `name` passed to `group()`) rather than composing with it.\n const baseResourceName = options.name || toCamelCase(ltrim(path, \"/\"));\n\n return this.group({ prefix: path, name: baseResourceName }, () => {\n const path = \"\";\n\n // clone the resource so we don't mess up with it\n const routeResource = resource;\n\n const isAcceptableResource = (type: ResourceMethod) => {\n return Boolean(\n // check if the route is not excluded\n (!options.except || !options.except.includes(type)) &&\n // check if the only option is set and the route is included\n (!options.only || options.only.includes(type)),\n );\n };\n\n if (routeResource.list && isAcceptableResource(\"list\")) {\n this.get(path, options.replace?.list || routeResource.list.bind(routeResource), {\n ...options,\n name: \"list\",\n restful: true,\n });\n }\n\n if (routeResource.get && isAcceptableResource(\"get\")) {\n this.get(path + \"/:id\", options.replace?.get || routeResource.get.bind(routeResource), {\n ...options,\n name: \"single\",\n restful: true,\n });\n }\n\n if (routeResource.create && isAcceptableResource(\"create\")) {\n const handler = options.replace?.create || this.manageValidation(routeResource, \"create\");\n\n this.post(path, handler, {\n ...options,\n name: \"create\",\n restful: true,\n });\n }\n\n if (routeResource.update && isAcceptableResource(\"update\")) {\n const handler = options.replace?.update || this.manageValidation(routeResource, \"update\");\n\n this.put(path + \"/:id\", handler, {\n ...options,\n name: \"update\",\n restful: true,\n });\n }\n\n if (routeResource.patch && isAcceptableResource(\"patch\")) {\n const handler = options.replace?.patch || this.manageValidation(routeResource, \"patch\");\n\n this.patch(path + \"/:id\", handler, {\n ...options,\n name: \"patch\",\n restful: true,\n });\n }\n\n if (routeResource.delete && isAcceptableResource(\"delete\")) {\n this.delete(\n path + \"/:id\",\n options.replace?.delete || routeResource.delete.bind(routeResource),\n {\n ...options,\n name: \"delete\",\n restful: true,\n },\n );\n }\n\n if (routeResource.bulkDelete && isAcceptableResource(\"delete\")) {\n this.delete(\n path,\n options.replace?.bulkDelete || routeResource.bulkDelete.bind(routeResource),\n {\n ...options,\n name: \"bulkDelete\",\n restful: true,\n },\n );\n }\n\n return this;\n });\n }\n\n /**\n * Group routes with options\n */\n public group(options: GroupedRoutesOptions, callback: RouterGroupCallback) {\n const {\n prefix,\n // name must always be defined because\n // if there are multiple groups without name\n // they might generate the same route name\n // thus causing an error\n // in this case we need always to make sure that\n // the name is always defined.\n name = prefix ? trim(prefix.replace(/\\//g, \".\"), \".\") : undefined,\n middleware,\n } = options;\n\n if (prefix) {\n this.stacks.prefix.push(prefix);\n }\n\n if (name) {\n this.stacks.name.push(name);\n }\n\n if (middleware) {\n this.stacks.middleware.push(...middleware);\n }\n\n try {\n callback();\n } finally {\n // Always pop/splice this group's stacks, even if the callback throws,\n // so a throwing group never leaks state onto the process-global singleton.\n if (prefix) {\n this.stacks.prefix.pop();\n }\n\n if (name) {\n this.stacks.name.pop();\n }\n\n if (middleware) {\n this.stacks.middleware.splice(\n this.stacks.middleware.length - middleware.length,\n middleware.length,\n );\n }\n }\n\n return this;\n }\n\n /**\n * Add prefix to all routes in the given callback\n */\n public prefix(prefix: string, callback: () => void) {\n return this.group({ prefix }, callback);\n }\n\n /**\n * Add API version prefix to all routes in the given callback\n * Automatically formats the version as /v{version}\n * @example\n * router.version(\"1\", () => {\n * router.get(\"/users\", getUsersV1); // /v1/users\n * });\n *\n * router.version(\"2\", () => {\n * router.get(\"/users\", getUsersV2); // /v2/users\n * });\n */\n public version(version: string | number, callback: () => void) {\n return this.prefix(`/v${version}`, callback);\n }\n\n /**\n * Wrap route additions with a source file path\n * Used for tracking which routes come from which file (for HMR)\n * @param sourceFile Relative path to the source file (e.g., \"src/app/users/routes.ts\")\n * @param callback Function that adds routes (will have sourceFile injected)\n */\n public async withSourceFile<T = any>(\n sourceFile: string,\n callback: () => T | Promise<T>,\n ): Promise<T | undefined> {\n // Set source file in stacks\n this.stacks.sourceFile = sourceFile;\n\n try {\n // Execute callback (routes added here will have sourceFile injected)\n return await callback();\n } catch (error) {\n // Log loudly, then RETHROW. Swallowing here silently dropped a whole\n // route file (duplicate name, invalid action, import error) so the\n // surface 404'd with no boot error. The caller decides what a throw\n // means: at boot it aborts the boot, during HMR the dev server's\n // batch-reload handler catches it, prints it, and keeps serving.\n log.error({\n module: \"router\",\n action: \"registerRoutes\",\n message: `Failed to register routes from \"${sourceFile}\"`,\n context: { sourceFile, error },\n });\n\n throw error;\n } finally {\n // Always clear source file from stacks so a throwing file never leaks\n // its sourceFile onto the process-global singleton.\n delete this.stacks.sourceFile;\n }\n }\n\n /**\n * Remove all routes that belong to a specific source file\n * Used when reloading routes files via HMR\n * @param sourceFile Relative path to the source file\n */\n public removeRoutesBySourceFile(sourceFile: string): void {\n if (this.routeReplacementTransaction) {\n this.routeReplacementTransaction.routes = this.routeReplacementTransaction.routes.filter(\n (route) => route.sourceFile !== sourceFile,\n );\n this.routeReplacementTransaction.removedSourceFiles.add(sourceFile);\n return;\n }\n\n this.routes = this.routes.filter((route) => route.sourceFile !== sourceFile);\n\n // Keep the signature diagnostics in step, so a reload that fixes a handler\n // stops reporting the version it replaced.\n forgetPositionalHandlerSuspects(sourceFile);\n\n this.routesVersion++;\n }\n\n /**\n * Atomically replace every route owned by the given exact source-file keys.\n *\n * The installer mutates an isolated draft. Public reads keep seeing the old\n * live table across awaits, and a failed installer discards every draft\n * mutation. A successful installer swaps the whole draft in one synchronous\n * commit and invalidates the dev route registry exactly once.\n */\n public async replaceRoutesBySourceFiles<T>(\n sourceFiles: Iterable<string>,\n install: () => T | Promise<T>,\n ): Promise<T> {\n if (this.routeReplacementTransaction) {\n throw new Error(\"Cannot nest route replacement transactions\");\n }\n\n const removedSourceFiles = new Set(sourceFiles);\n\n this.routeReplacementTransaction = {\n routes: this.routes.filter((route) => !removedSourceFiles.has(route.sourceFile)),\n removedSourceFiles,\n addedRoutes: [],\n };\n\n try {\n const result = await install();\n const transaction = this.routeReplacementTransaction!;\n\n this.routes = transaction.routes;\n this.routeReplacementTransaction = undefined;\n\n // Diagnostic state follows the same commit boundary as the route table.\n // Added routes were deliberately not inspected while still speculative.\n for (const sourceFile of transaction.removedSourceFiles) {\n forgetPositionalHandlerSuspects(sourceFile);\n }\n\n const committedRoutes = new Set(transaction.routes);\n\n for (const route of transaction.addedRoutes) {\n if (committedRoutes.has(route)) {\n inspectHandlerSignature(route.handler, route);\n }\n }\n\n this.routesVersion++;\n\n return result;\n } catch (error) {\n this.routeReplacementTransaction = undefined;\n throw error;\n }\n }\n\n /**\n * Manage validation system for the given resource\n */\n private manageValidation(resource: RouteResource, method: \"create\" | \"update\" | \"patch\") {\n const handler = resource[method]?.bind(resource) as RequestHandler;\n\n const methodValidation = resource?.validation?.[method];\n\n if (method === \"patch\") {\n handler.validation = methodValidation;\n\n if (handler.validation?.validate) {\n handler.validation.validate = handler.validation.validate.bind(resource);\n }\n\n if (resource.validation?.patch) {\n handler.validation = merge(resource.validation.patch, handler.validation);\n }\n\n return handler;\n }\n\n if (!resource.validation || (!methodValidation && !resource.validation.all)) return handler;\n\n if (resource.validation.all) {\n const validationMethods = {\n all: resource?.validation?.all?.validate,\n [method]: methodValidation?.validate,\n };\n\n const validation: RequestHandlerValidation = {};\n\n if (resource.validation.all.schema || methodValidation?.schema) {\n if (!methodValidation?.schema && resource.validation.all.schema) {\n // Case 2: Only all.schema exists - clone it for this method\n validation.schema = resource.validation.all.schema;\n } else if (methodValidation?.schema && resource.validation.all.schema) {\n // Case 3: Both exist - merge them (all is base, method overrides)\n validation.schema = resource.validation.all.schema.merge(methodValidation.schema);\n } else if (methodValidation?.schema && !resource.validation.all.schema) {\n // Case 1: Only method schema exists - use it directly\n validation.schema = methodValidation.schema;\n }\n // Case 4: Neither exists - handled by outer if being false\n }\n\n if (validationMethods.all || validationMethods[method]) {\n validation.validate = async ({ request, response }: HttpContext) => {\n if (validationMethods.all) {\n const output = await validationMethods.all.call(resource, { request, response });\n\n if (output) return output;\n }\n\n if (validationMethods[method]) {\n return await validationMethods[method]?.call(resource, { request, response });\n }\n\n return;\n };\n }\n\n if (!isEmpty(validation)) {\n handler.validation = validation;\n }\n } else {\n handler.validation = resource.validation[method];\n\n if (handler.validation?.validate) {\n handler.validation.validate = handler.validation.validate.bind(resource);\n }\n }\n\n return handler;\n }\n\n /**\n * Get all routes list\n */\n public list() {\n return this.routes;\n }\n\n /**\n * Return fresh browser-safe snapshots of named, non-page routes.\n *\n * Names are the registered names, including method suffixes. `all` stays\n * intact as route metadata; consumers decide whether their use supports it.\n */\n public getNamedApiRoutes(): readonly NamedApiRoute[] {\n return Object.freeze(\n this.routes\n .filter((route) => !route.isPage && typeof route.name === \"string\" && route.name.length > 0)\n .map((route) => Object.freeze({ name: route.name!, path: route.path, method: route.method })),\n );\n }\n\n /**\n * Number of routes currently registered on the singleton.\n *\n * Used as a readiness signal: a successful boot that ends up with zero\n * routes almost always means a route module failed to register silently\n * (see `withSourceFile`), so callers can surface that instead of letting\n * the whole surface 404.\n */\n public routeCount(): number {\n return this.routes.length;\n }\n\n /**\n * Register routes to the server\n */\n public scan(server: FastifyInstance) {\n // Every route is registered by the time we scan, so this is the first\n // moment the whole list can be reported at once — and it is still before a\n // single request is served.\n reportPositionalHandlerSuspects();\n\n this.eventListeners.beforeScan?.forEach((callback) => callback(this, server));\n\n // Fastify automatically exposes HEAD for every GET route. When an app\n // declares its own HEAD route at the same path, suppress only that GET\n // route's implicit registration so the explicit handler owns HEAD,\n // regardless of declaration order.\n const explicitHeadPaths = new Set(\n this.routes\n .filter((route) => route.method.toLowerCase() === \"head\")\n .map((route) => route.path),\n );\n\n this.routes.forEach((route) => {\n const requestMethod = route.method.toLowerCase();\n const requestMethodFunction = server[requestMethod].bind(server);\n\n const options = {\n ...route.serverOptions,\n ...(requestMethod === \"get\" &&\n explicitHeadPaths.has(route.path) && { exposeHeadRoute: false }),\n config: {\n ...route.serverOptions?.config,\n ...(route.rateLimit && { rateLimit: buildRouteRateLimit(route.rateLimit) }),\n },\n };\n\n requestMethodFunction(\n route.path,\n options,\n async (baseRequest: FastifyRequest, reply: FastifyReply) => {\n const { output, response } = await this.handleRoute(route)(baseRequest, reply);\n\n return output || response.baseResponse;\n },\n );\n });\n\n for (const directoryOptions of this.staticDirectories) {\n server.register(fastifyStatic, {\n ...directoryOptions,\n decorateReply: false,\n });\n }\n\n this.eventListeners.afterScanning?.forEach((callback) => callback(this, server));\n }\n\n /**\n * Scan routes for the development server\n * Uses wildcard routing with find-my-way for HMR support\n */\n public scanDevServer(server: FastifyInstance) {\n // Same boot-time report as production `scan`. Routes reloaded later by HMR\n // are still recorded, but only surface on the next scan or via\n // `warlock doctor`.\n reportPositionalHandlerSuspects();\n\n this.eventListeners.beforeScan?.forEach((callback) => callback(this, server));\n\n let routeRegistry: RouteRegistry | undefined;\n let registryVersion = -1;\n\n const applyDevRateLimit = createDevRateLimiter(server);\n\n // Rebuilt when the route table changes rather than per request. Building it\n // inside the handler re-registered every route on every hit — and `all`\n // routes expand into seven registrations each. Keyed on `routesVersion`\n // rather than on the route count, so an HMR reload that swaps a route\n // without changing the count still invalidates.\n const resolveRouteRegistry = () => {\n if (routeRegistry && registryVersion === this.routesVersion) {\n return routeRegistry;\n }\n\n routeRegistry = new RouteRegistry();\n\n routeRegistry.register(this.routes);\n\n registryVersion = this.routesVersion;\n\n return routeRegistry;\n };\n\n // Matching happens here, in Fastify's own onRequest phase, so a route's\n // `serverOptions.onRequest` still runs BEFORE body parsing. Production\n // `scan()` gets that from per-route registration; the wildcard dispatcher\n // has no per-route slot, so without this the hook silently never runs.\n server.addHook(\n \"onRequest\",\n async (fastifyRequest: FastifyRequest, fastifyReply: FastifyReply) => {\n // Only requests Fastify routed to the dev wildcard belong to the app's\n // router. A plugin's own route (devtools' `/__warlock/api/requests/:id`)\n // must keep its params even when an app catch-all matches the URL too.\n if (fastifyRequest.routeOptions.url !== \"*\") {\n return undefined;\n }\n\n const match = resolveRouteRegistry().find(fastifyRequest.method, fastifyRequest.url);\n\n if (!match) {\n return undefined;\n }\n\n (fastifyRequest as DevDispatchRequest).matchedDevRoute = match;\n\n fastifyRequest.params = match.params;\n\n // Same slot production gives it: the limiter runs first in onRequest,\n // ahead of the route's own hooks.\n await applyDevRateLimit(match.route, fastifyRequest, fastifyReply);\n\n if (fastifyReply.sent) {\n return fastifyReply;\n }\n\n return runRouteHooks(match.route, \"onRequest\", fastifyRequest, fastifyReply);\n },\n );\n\n for (const phase of FORWARDED_ROUTE_PHASES.filter((name) => name !== \"onRequest\")) {\n server.addHook(phase, async (fastifyRequest: FastifyRequest, fastifyReply: FastifyReply) => {\n const match = (fastifyRequest as DevDispatchRequest).matchedDevRoute;\n\n if (!match) {\n return undefined;\n }\n\n return runRouteHooks(match.route, phase, fastifyRequest, fastifyReply);\n });\n }\n\n // Shared handler for wildcard routing\n const wildcardHandler = async (fastifyRequest: FastifyRequest, fastifyReply: FastifyReply) => {\n const match = (fastifyRequest as DevDispatchRequest).matchedDevRoute;\n\n // No match found - return 404\n if (!match) {\n return fastifyReply\n .code(404)\n .send(buildNotFoundBody(fastifyRequest.method, fastifyRequest.url));\n }\n\n try {\n // Call the matched route handler\n const { output, response } = await this.handleRoute(match.route)(\n fastifyRequest,\n fastifyReply,\n );\n\n return output || response.baseResponse;\n } catch (error) {\n log.error(\"router\", \"dev-dispatch\", error as Error, {\n method: fastifyRequest.method,\n url: fastifyRequest.url,\n });\n\n throw error;\n }\n };\n\n // Every verb production can register. Fastify's implicit HEAD for the GET\n // wildcard is switched off so the HEAD wildcard owns it (the registry falls\n // back to the GET route, exactly as production's implicit HEAD does).\n // `@fastify/cors` registers its own OPTIONS \"*\" catch-all whenever\n // preflight is on. Plugins load after this runs, so `hasRoute` cannot see\n // it yet: decide from the same options the cors plugin receives.\n const corsOwnsPreflight = buildCorsOptions().preflight !== false;\n\n for (const method of DEV_DISPATCH_METHODS) {\n if (method === \"OPTIONS\" && (corsOwnsPreflight || server.hasRoute({ method: \"OPTIONS\", url: \"*\" }))) {\n continue;\n }\n\n server.route({\n method,\n url: \"*\",\n ...(method === \"GET\" && { exposeHeadRoute: false }),\n handler: wildcardHandler,\n });\n }\n\n // Register static directories\n for (const directoryOptions of this.staticDirectories) {\n server.register(fastifyStatic, {\n ...directoryOptions,\n decorateReply: false,\n });\n }\n\n this.eventListeners.afterScanning?.forEach((callback) => callback(this, server));\n }\n\n /**\n * Get the route path for the given route name\n */\n public getRoute(name: string, params: Record<string, any> = {}) {\n const route = this.routes.find((route) => route.name === name);\n\n if (!route) {\n throw new Error(`Route name \"${name}\" not found`);\n }\n\n const used = new Set<string>();\n\n const path = route.path.replace(/:([A-Za-z0-9_]+)(\\?)?/g, (_match, key: string, optional) => {\n const value = params[key];\n\n if (value === undefined || value === null) {\n if (optional) return \"\";\n\n throw new Error(`Route \"${name}\" is missing the \"${key}\" param`);\n }\n\n used.add(key);\n\n return encodeURIComponent(String(value));\n });\n\n const query = Object.keys(params)\n .filter((key) => !used.has(key) && params[key] !== undefined && params[key] !== null)\n .map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(String(params[key]))}`)\n .join(\"&\");\n\n return query ? `${path}?${query}` : path;\n }\n\n /**\n * Handle the given route\n */\n private handleRoute(route: Route) {\n return async (fastifyRequest: FastifyRequest, fastifyResponse: FastifyReply) => {\n const request = new Request();\n const response = new Response();\n response.setResponse(fastifyResponse);\n request.response = response;\n\n response.request = request;\n\n // \"route.match\" tracing phase: the pattern is\n // already known here (`route.path`), so this brackets the cost of\n // stamping the request/route onto the `Request` instance rather than\n // route-registry matching itself, which happens upstream of this\n // function for both the production `scan()` path and the dev wildcard\n // dispatcher (both funnel into `handleRoute`).\n const tracingEnabled = isTracingEnabled();\n const routeMatchStartedAt = tracingEnabled ? performance.now() : 0;\n\n request.setRequest(fastifyRequest).setRoute(route);\n\n if (tracingEnabled) {\n dispatchPhase(buildTracingContext(request), {\n name: \"route.match\",\n durationMs: performance.now() - routeMatchStartedAt,\n attrs: { route: route.path },\n });\n }\n\n /*\n Both ends of the entry, not just the start — see\n `log-request-lifecycle.ts`. A start line on its own made a hung request\n and an instant one look identical, and the completion line is what makes\n a MISSING one legible as a hang.\n */\n const result = await logRequestLifecycle(\n {\n info: (entry) => log.info(entry),\n warn: (entry) => log.warn(entry),\n error: (entry) => log.error(entry),\n now: () => performance.now(),\n },\n {\n module: \"route\",\n action: describeRouteForLog(route.method, route.path),\n requestId: request.id,\n context: { request, response },\n request,\n // Read after the run: the status is decided during the request.\n statusCode: () => fastifyResponse.statusCode,\n },\n () => request.execute(),\n );\n\n // A handler may return a plain object (`ReturnedResponse`). Route it\n // through `Response.send` so status, events and hooks apply, exactly as\n // middleware outputs already do.\n let output = result;\n\n if (\n output !== undefined &&\n output !== null &&\n !(output instanceof Response) &&\n (output as unknown) !== fastifyResponse\n ) {\n output = await response.send(output);\n }\n\n return {\n output,\n response,\n request,\n };\n };\n }\n}\n\nexport const router = Router.getInstance();\n\ncontainer.set(\"router\", router);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0DA,MAAM,yBAAyB;CAAC;CAAa;CAAiB;AAAY;AAc1E,SAAS,WACP,MACsB;CACtB,IAAI,CAAC,MACH,OAAO,CAAC;CAGV,OAAO,MAAM,QAAQ,IAAI,IAAI,OAAO,CAAC,IAAI;AAC3C;;;;;;;;AASA,eAAe,cACb,OACA,OACA,SACA,OACA;CACA,MAAM,QAAQ,WACZ,MAAM,gBAAgB,MACxB;CAEA,KAAK,MAAM,QAAQ,OAGjB,IAAI,MAFkB,KAAK,SAAS,KAAK,MAE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kC;GAC9E,MAAM,UAAU,IAAI,QAAQ;GAC5B,MAAM,WAAW,IAAI,SAAS;GAC9B,SAAS,YAAY,eAAe;GACpC,QAAQ,WAAW;GAEnB,SAAS,UAAU;GAQnB,MAAM,iBAAiB,iBAAiB;GACxC,MAAM,sBAAsB,iBAAiB,YAAY,IAAI,IAAI;GAEjE,QAAQ,WAAW,cAAc,CAAC,CAAC,SAAS,KAAK;GAEjD,IAAI,gBACF,cAAc,oBAAoB,OAAO,GAAG;IAC1C,MAAM;IACN,YAAY,YAAY,IAAI,IAAI;IAChC,OAAO,EAAE,OAAO,MAAM,KAAK;GAC7B,CAAC;GA+BH,IAAI,SAAS,MAtBQ,oBACnB;IACE,OAAO,UAAU,IAAI,KAAK,KAAK;IAC/B,OAAO,UAAU,IAAI,KAAK,KAAK;IAC/B,QAAQ,UAAU,IAAI,MAAM,KAAK;IACjC,WAAW,YAAY,IAAI;GAC7B,GACA;IACE,QAAQ;IACR,QAAQ,oBAAoB,MAAM,QAAQ,MAAM,IAAI;IACpD,WAAW,QAAQ;IACnB,SAAS;KAAE;KAAS;IAAS;IAC7B;IAEA,kBAAkB,gBAAgB;GACpC,SACM,QAAQ,QAAQ,CACxB;GAOA,IACE,WAAW,UACX,WAAW,QACX,EAAE,kBAAkB,aACnB,WAAuB,iBAExB,SAAS,MAAM,SAAS,KAAK,MAAM;GAGrC,OAAO;IACL;IACA;IACA;GACF;EACF;CACF;AACF;AAEA,MAAa,SAAS,OAAO,YAAY;AAEzC,UAAU,IAAI,UAAU,MAAM"}
|
package/esm/router/types.d.mts
CHANGED
|
@@ -34,7 +34,8 @@ type RequestHandlerValidation<TRequest extends Request = Request> = {
|
|
|
34
34
|
validate?: Middleware<TRequest>;
|
|
35
35
|
/**
|
|
36
36
|
* Define what should be validated
|
|
37
|
-
* If not passed,
|
|
37
|
+
* If not passed, validates body and query plus route params whose names are
|
|
38
|
+
* declared by the object schema. Body and query values take precedence.
|
|
38
39
|
*/
|
|
39
40
|
validating?: ("body" | "query" | "params" | "headers")[];
|
|
40
41
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.mts","names":[],"sources":["../../../../../../../core/src/router/types.ts"],"mappings":";;;;;;;;;;;;KASY,kBAAA,GAAqB,gBAAgB;;AAAjD;;;;AAAiD;KAQrC,UAAA,2BAAqC,OAAA,GAAU,OAAA;EAAA,CACxD,OAAA,EAAS,WAAA,CAAY,iBAAA,IAAqB,kBAAA;AAAA;AAAA,KAGjC,mBAAA;AAAA,KAEA,kBAAA,GAAqB,cAAA,SAAuB,aAAa;;;;KAKzD,cAAA;AAAA,KAEA,iBAAA,GAAoB,MAAM,UAAU,UAAA;AAAA,KAEpC,wBAAA,kBAA0C,OAAA,GAAU,OAAA;EAff;;;EAmB/C,QAAA,GAAW,UAAA,CAAW,QAAA;EAlBrB;;;AAA4D;
|
|
1
|
+
{"version":3,"file":"types.d.mts","names":[],"sources":["../../../../../../../core/src/router/types.ts"],"mappings":";;;;;;;;;;;;KASY,kBAAA,GAAqB,gBAAgB;;AAAjD;;;;AAAiD;KAQrC,UAAA,2BAAqC,OAAA,GAAU,OAAA;EAAA,CACxD,OAAA,EAAS,WAAA,CAAY,iBAAA,IAAqB,kBAAA;AAAA;AAAA,KAGjC,mBAAA;AAAA,KAEA,kBAAA,GAAqB,cAAA,SAAuB,aAAa;;;;KAKzD,cAAA;AAAA,KAEA,iBAAA,GAAoB,MAAM,UAAU,UAAA;AAAA,KAEpC,wBAAA,kBAA0C,OAAA,GAAU,OAAA;EAff;;;EAmB/C,QAAA,GAAW,UAAA,CAAW,QAAA;EAlBrB;;;AAA4D;AAG/D;EAqBE,UAAA;;;AArB6B;EAyB7B,MAAA,GAAS,eAAA;AAAA;AAAA,UAGM,yBAAA;EA1BgB;AAAoC;AAKrE;EAyBE,OAAA,EAAS,OAAA;;;AAzBe;EA6BxB,QAAA,EAAU,QAAA;EA3BiB;;;EA+B3B,OAAA,IAAW,OAAA,CAAQ,gBAAA;E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A,YAAA;EAyBI;AAAA;AAIN;EAzBE,SAAA,GAAY,YAAA;AAAA;AAAA,KAGF,WAAA,oBAA+B,CAAA,IAAK,IAAA,CAAK,CAAA,EAAG,CAAA,IAAK,OAAA,CAAQ,IAAA,CAAK,CAAA,EAAG,CAAA;;;;KAKjE,oBAAA;EAyCD;;;EArCT,UAAA,GAAa,UAAU;EAyDZ;;;EArDX,MAAA;EAaA;;;;EARA,IAAA;AAAA;;KAIU,aAAA;EAoBV;;;EAhBA,IAAA,GAAO,cAAA;EAwBP;;;EApBA,GAAA,GAAM,cAAA;EA4BE;;;EAxBR,MAAA,GAAS,cAAA;EAgCE;;;EA5BX,MAAA,GAAS,cAAA;EAgCyB;AAIpC;;EAhCE,KAAA,GAAQ,cAAA;EAmCc;;;EA/BtB,MAAA,GAAS,cAAA;EA+BG;;;EA3BZ,UAAA,GAAa,cAAA;;;;EAIb,UAAA;;;;IAIE,GAAA,GAAM,wBAAA;;;;IAIN,MAAA,GAAS,wBAAA;;;;IAIT,MAAA,GAAS,wBAAA;;;;IAIT,KAAA,GAAQ,wBAAA;EAAA;AAAA;AAAA,KAIA,YAAA;EACV,MAAA;EACA,IAAA;EACA,UAAA,EAAY,UAAU;;;;EAItB,UAAA;AAAA"}
|
package/esm/tests/index.d.mts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
+
import { assertPortIsAvailable, isPortAvailable } from "../http/port-preflight.mjs";
|
|
1
2
|
import { StartHttpTestServerOptions, isTestServerRunning, startHttpTestServer, stopHttpTestServer } from "./start-http-development-server.mjs";
|
|
2
3
|
import { expectJson, getTestServerUrl, parseJsonResponse, testDelete, testGet, testPatch, testPost, testPut, testRequest } from "./test-helpers.mjs";
|
|
3
4
|
import { TestConnectorsSelection } from "./test-connectors-selection.mjs";
|
|
4
|
-
import { TestLifecycleError, TestSetupOptions, setupTest, teardownTest } from "./vitest-setup.mjs";
|
|
5
|
-
export { StartHttpTestServerOptions, type TestConnectorsSelection, TestLifecycleError, TestSetupOptions, expectJson, getTestServerUrl, isTestServerRunning, parseJsonResponse, setupTest, startHttpTestServer, stopHttpTestServer, teardownTest, testDelete, testGet, testPatch, testPost, testPut, testRequest };
|
|
5
|
+
import { TestLifecycleError, TestSetupOptions, setupTest, teardownTest, warnMissingImportModule } from "./vitest-setup.mjs";
|
|
6
|
+
export { StartHttpTestServerOptions, type TestConnectorsSelection, TestLifecycleError, TestSetupOptions, assertPortIsAvailable, expectJson, getTestServerUrl, isPortAvailable, isTestServerRunning, parseJsonResponse, setupTest, startHttpTestServer, stopHttpTestServer, teardownTest, testDelete, testGet, testPatch, testPost, testPut, testRequest, warnMissingImportModule };
|
package/esm/tests/index.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
+
import { assertPortIsAvailable, isPortAvailable } from "../http/port-preflight.mjs";
|
|
1
2
|
import { isTestServerRunning, startHttpTestServer, stopHttpTestServer } from "./start-http-development-server.mjs";
|
|
2
3
|
import { expectJson, getTestServerUrl, parseJsonResponse, testDelete, testGet, testPatch, testPost, testPut, testRequest } from "./test-helpers.mjs";
|
|
3
|
-
import { TestLifecycleError, setupTest, teardownTest } from "./vitest-setup.mjs";
|
|
4
|
+
import { TestLifecycleError, setupTest, teardownTest, warnMissingImportModule } from "./vitest-setup.mjs";
|
|
4
5
|
|
|
5
|
-
export { TestLifecycleError, expectJson, getTestServerUrl, isTestServerRunning, parseJsonResponse, setupTest, startHttpTestServer, stopHttpTestServer, teardownTest, testDelete, testGet, testPatch, testPost, testPut, testRequest };
|
|
6
|
+
export { TestLifecycleError, assertPortIsAvailable, expectJson, getTestServerUrl, isPortAvailable, isTestServerRunning, parseJsonResponse, setupTest, startHttpTestServer, stopHttpTestServer, teardownTest, testDelete, testGet, testPatch, testPost, testPut, testRequest, warnMissingImportModule };
|