@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":"tracing.type.d.mts","names":[],"sources":["../../../../../../../../core/src/http/tracing/tracing.type.ts"],"mappings":";;AAkBA;;;;;;;;;;AAUM;AAIN;;;;;KAdY,cAAA;
|
|
1
|
+
{"version":3,"file":"tracing.type.d.mts","names":[],"sources":["../../../../../../../../core/src/http/tracing/tracing.type.ts"],"mappings":";;AAkBA;;;;;;;;;;AAUM;AAIN;;;;;KAdY,cAAA;EAkBV;;;;EAbA,OAAA,UAkBU;EAhBV,SAAA;EACA,MAAA;EACA,KAAA;EACA,IAAA;AAAA;;KAIU,gBAAA;EACV,IAAA;EACA,UAAA,UAoBsB;EAlBtB,SAAA;EACA,KAAA,GAAQ,MAAM;AAAA;;KAIJ,qBAAA;EACV,MAAA;EACA,UAAA;EACA,KAAA;AAAA;;;;;;;;KAUU,YAAA;EACV,cAAA,EAAgB,GAAA,EAAK,cAAA;EACrB,YAAA,EAAc,GAAA,EAAK,cAAA,EAAgB,MAAA,EAAQ,qBAAA;EAC3C,OAAA,EAAS,GAAA,EAAK,cAAA,EAAgB,KAAA,EAAO,gBAAA;AAAA;;AAAgB;AASvD;;;;KAAY,iBAAA;EAGV,qBADA,OAAA;EACA,KAAA,GAAQ,YAAY;AAAA"}
|
package/esm/http/types.d.mts
CHANGED
|
@@ -179,6 +179,15 @@ interface PartialMiddleware {
|
|
|
179
179
|
* Http Configurations list
|
|
180
180
|
*/
|
|
181
181
|
interface HttpConfigurations {
|
|
182
|
+
/**
|
|
183
|
+
* Status used when a Cascade model fails validation during a database write.
|
|
184
|
+
* The default is 500 because request input has already been validated before
|
|
185
|
+
* a model write begins; set this only when an application deliberately needs
|
|
186
|
+
* a different response status.
|
|
187
|
+
*
|
|
188
|
+
* @default 500
|
|
189
|
+
*/
|
|
190
|
+
modelValidationErrorStatus?: number;
|
|
182
191
|
/**
|
|
183
192
|
* Server port
|
|
184
193
|
*/
|
package/esm/http/types.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.mts","names":[],"sources":["../../../../../../../core/src/http/types.ts"],"mappings":";;;;;;;;;;KASY,YAAA;;;AAAZ;;;;AAAwB;AA0BxB;;;;AAca;AAeb;;;;AACU;AAMV;;;;;;UApCiB,aAAA;EAoDL;;;;;;;;;;;;;EAtCV,WAAW;AAAA;;;;AAmDY;AAiEzB;;;;;;;;KArGY,kBAAA;EACV,QAAQ;AAAA;;;;KAME,gBAAA;;;;AAIR;;;;EAIA,OAAA,CAAQ,QAAA;;;;EAIR,MAAA;;;;EAIA,OAAA,CAAQ,MAAA;;;;;;;;EAQR,OAAA;;;;KAKQ,aAAA
|
|
1
|
+
{"version":3,"file":"types.d.mts","names":[],"sources":["../../../../../../../core/src/http/types.ts"],"mappings":";;;;;;;;;;KASY,YAAA;;;AAAZ;;;;AAAwB;AA0BxB;;;;AAca;AAeb;;;;AACU;AAMV;;;;;;UApCiB,aAAA;EAoDL;;;;;;;;;;;;;EAtCV,WAAW;AAAA;;;;AAmDY;AAiEzB;;;;;;;;KArGY,kBAAA;EACV,QAAQ;AAAA;;;;KAME,gBAAA;;;;AAIR;;;;EAIA,OAAA,CAAQ,QAAA;;;;EAIR,MAAA;;;;EAIA,OAAA,CAAQ,MAAA;;;;;;;;EAQR,OAAA;;;;KAKQ,aAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqViB;AAG7B;;;;;;;;;;;;;;AAmBA;;;AAAA;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;;;;;;;EAOV,IAAA,GAAO,KAAA,UAAe,IAAA,OAAW,EAAA,cAAgB,qBAAA;;;;EAIjD,OAAA,GAAU,OAAA,aAAoB,qBAAA;;;;EAI9B,GAAA,QAAW,qBAAA;;;;;EAKX,YAAA,GAAe,OAAA,iBAAwB,qBAAA;;;;EAIvC,KAAA;AAAA"}
|
package/esm/image/image.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"image.mjs","names":[],"sources":["../../../../../../../core/src/image/image.ts"],"sourcesContent":["import { createRequire } from \"node:module\";\r\nimport type sharp from \"sharp\";\r\nimport type { FormatEnum } from \"sharp\";\r\nimport { safeFetchToBuffer } from \"../storage/utils/safe-fetch\";\r\n\r\n// ============================================================\r\n// Lazily Resolved Sharp Module\r\n// ============================================================\r\n\r\n/**\r\n * Installation instructions for sharp\r\n */\r\nconst SHARP_INSTALL_INSTRUCTIONS = `\r\nImage processing requires the sharp package.\r\nInstall it with:\r\n\r\n warlock add image\r\n\r\nOr manually:\r\n\r\n npm install sharp\r\n pnpm add sharp\r\n yarn add sharp\r\n`.trim();\r\n\r\n/**\r\n * Cached sharp function, populated by the first `resolveSharp()` call\r\n */\r\nlet sharpFn: typeof sharp | null = null;\r\n\r\n/**\r\n * Whether the resolution attempt already ran (success or failure)\r\n */\r\nlet sharpResolved = false;\r\n\r\n/**\r\n * Why the resolution failed, when it failed for a reason other than absence.\r\n *\r\n * Cached and re-thrown on every later call: the resolution attempt runs exactly\r\n * once, so without this the second construction would fall through to the\r\n * \"not installed\" branch and report a different, wrong cause.\r\n */\r\nlet sharpLoadError: Error | null = null;\r\n\r\n/**\r\n * `new Error(message, { cause })` is ES2022, and this package still compiles\r\n * against the ES2020 lib (see #16), where `Error` is typed as taking a message\r\n * only. Node has supported the option since v16, so this is the type layer\r\n * catching up with the runtime, not a change in what the code does.\r\n */\r\ntype ErrorWithCauseConstructor = new (message: string, options: { cause: unknown }) => Error;\r\n\r\nconst ErrorWithCause = Error as ErrorWithCauseConstructor;\r\n\r\n/**\r\n * Whether `error` says sharp itself is absent, as opposed to present but broken.\r\n *\r\n * Both halves are load-bearing. `MODULE_NOT_FOUND` alone is not enough: a\r\n * dependency missing *inside* sharp raises the very same code (`Cannot find\r\n * module 'color'`), and treating that as absence would tell the operator to\r\n * install a package they already have. So the message has to name the specifier\r\n * `'sharp'` exactly — quoted, which is also what keeps `'sharp-cli'` and friends\r\n * from matching.\r\n */\r\nfunction isSharpMissing(error: unknown): boolean {\r\n if (!(error instanceof Error)) return false;\r\n\r\n return (\r\n (error as NodeJS.ErrnoException).code === \"MODULE_NOT_FOUND\" &&\r\n error.message.includes(\"Cannot find module 'sharp'\")\r\n );\r\n}\r\n\r\n/**\r\n * Resolve sharp synchronously, on first use.\r\n *\r\n * Resolution is deliberately *lazy* and *synchronous*:\r\n *\r\n * - Lazy, because a top-level require would drag sharp's native binary into\r\n * every `import \"@warlock.js/core\"`, including apps that never touch images.\r\n * - Synchronous, because the `Image` constructor is synchronous. An async\r\n * import kicked off at module load leaves a window in which the module is\r\n * neither loaded nor known to be missing, and a constructor running inside\r\n * that window has no correct answer to give.\r\n *\r\n * `createRequire` gives an ESM-safe `require`, and the outcome — module, absence\r\n * or load failure — is cached, so the resolution runs exactly once per process.\r\n * The failure *reason* is cached too, not just the fact of it: every call after\r\n * a failed load has to report the same cause as the first one.\r\n *\r\n * @throws when sharp is not installed, or is installed but cannot be loaded\r\n */\r\nfunction resolveSharp(): typeof sharp {\r\n if (!sharpResolved) {\r\n sharpResolved = true;\r\n\r\n try {\r\n const require = createRequire(import.meta.url);\r\n const module = require(\"sharp\");\r\n sharpFn = (module.default ?? module) as typeof sharp;\r\n } catch (error) {\r\n sharpFn = null;\r\n\r\n if (!isSharpMissing(error)) {\r\n // sharp is there, it just would not load — almost always a binary built\r\n // for another platform. Its own error names the runtime and the fix, so\r\n // it is inlined *and* chained: a terminal that never prints `cause`\r\n // must still show the text that actually helps.\r\n sharpLoadError = new ErrorWithCause(`Failed to load \"sharp\": ${(error as Error).message}`, {\r\n cause: error,\r\n });\r\n }\r\n }\r\n }\r\n\r\n if (sharpLoadError) {\r\n throw sharpLoadError;\r\n }\r\n\r\n if (!sharpFn) {\r\n throw new Error(`sharp is not installed.\\n\\n${SHARP_INSTALL_INSTRUCTIONS}`);\r\n }\r\n\r\n return sharpFn;\r\n}\r\n\r\n// ============================================================\r\n// Types\r\n// ============================================================\r\n\r\nexport type ImageFormat = keyof FormatEnum;\r\n\r\nexport type ImageInput = string | Buffer | Uint8Array | ArrayBuffer;\r\n\r\n/**\r\n * Watermark configuration for deferred execution\r\n */\r\nexport type WatermarkConfig = {\r\n image: ImageInput | Image;\r\n options: sharp.OverlayOptions;\r\n};\r\n\r\n/**\r\n * Operation descriptor for deferred pipeline execution.\r\n * All operations are stored and executed at save/toBuffer time.\r\n */\r\ntype ImageOperation =\r\n | { type: \"resize\"; options: sharp.ResizeOptions }\r\n | { type: \"crop\"; options: sharp.Region }\r\n | { type: \"rotate\"; angle: number }\r\n | { type: \"flip\" }\r\n | { type: \"flop\" }\r\n | { type: \"blur\"; sigma: number }\r\n | { type: \"sharpen\"; options?: sharp.SharpenOptions }\r\n | { type: \"blackAndWhite\" }\r\n | { type: \"opacity\"; value: number }\r\n | { type: \"negate\"; options?: sharp.NegateOptions }\r\n | { type: \"tint\"; color: sharp.Color }\r\n | { type: \"trim\"; options?: sharp.TrimOptions }\r\n | { type: \"watermark\"; config: WatermarkConfig }\r\n | { type: \"watermarks\"; configs: WatermarkConfig[] };\r\n\r\n/**\r\n * Transformation options that can be applied in batch via `apply()` method.\r\n *\r\n * **Execution Order (when using apply()):**\r\n * 1. resize - Resize first to work with correct dimensions\r\n * 2. crop - Crop after resize to extract the desired region\r\n * 3. rotate - Rotation after sizing\r\n * 4. flip/flop - Mirror operations\r\n * 5. blackAndWhite/grayscale - Color space conversion\r\n * 6. blur - Blur effect\r\n * 7. sharpen - Sharpen effect\r\n * 8. tint - Color overlay\r\n * 9. negate - Invert colors\r\n * 10. opacity - Transparency (applied via composite)\r\n * 11. format/quality - Applied on save/export\r\n */\r\nexport type ImageTransformOptions = {\r\n /**\r\n * Output quality (1-100), applied based on final format\r\n */\r\n quality?: number;\r\n /**\r\n * Output format (jpeg, png, webp, avif, etc.)\r\n */\r\n format?: ImageFormat;\r\n /**\r\n * Resize options\r\n */\r\n resize?: sharp.ResizeOptions;\r\n /**\r\n * Crop/extract region\r\n */\r\n crop?: sharp.Region;\r\n /**\r\n * Rotation angle in degrees\r\n */\r\n rotate?: number;\r\n /**\r\n * Flip vertically (top to bottom)\r\n */\r\n flip?: boolean;\r\n /**\r\n * Flop horizontally (left to right)\r\n */\r\n flop?: boolean;\r\n /**\r\n * Convert to black and white\r\n */\r\n blackAndWhite?: boolean;\r\n /**\r\n * Alias for blackAndWhite\r\n */\r\n grayscale?: boolean;\r\n /**\r\n * Blur sigma (must be >= 0.3)\r\n */\r\n blur?: number;\r\n /**\r\n * Sharpen options\r\n */\r\n sharpen?: sharp.SharpenOptions | boolean;\r\n /**\r\n * Tint color\r\n */\r\n tint?: sharp.Color;\r\n /**\r\n * Negate/invert colors\r\n */\r\n negate?: sharp.NegateOptions | boolean;\r\n /**\r\n * Opacity (0-100)\r\n */\r\n opacity?: number;\r\n /**\r\n * Trim options\r\n */\r\n trim?: sharp.TrimOptions | boolean;\r\n /**\r\n * Single watermark\r\n */\r\n watermark?: WatermarkConfig;\r\n /**\r\n * Multiple watermarks\r\n */\r\n watermarks?: WatermarkConfig[];\r\n};\r\n\r\n/**\r\n * Internal options stored for deferred application\r\n */\r\ntype InternalOptions = {\r\n quality?: number;\r\n format?: ImageFormat;\r\n};\r\n\r\n/**\r\n * Image manipulation class with deferred pipeline execution.\r\n *\r\n * **Important:** This class requires the `sharp` package to be installed.\r\n * Install it with: `warlock add image` or `npm install sharp`\r\n *\r\n * Sharp is resolved synchronously on the first construction that needs it, so\r\n * the constructor and all chainable methods remain synchronous, and a missing\r\n * sharp throws at construction rather than at some later await.\r\n *\r\n * All operations are synchronous and stored as descriptors.\r\n * The pipeline is executed only when calling output methods:\r\n * - `save()` - Save to file\r\n * - `toBuffer()` - Get as buffer\r\n * - `toBase64()` - Get as base64 string\r\n * - `toDataUrl()` - Get as data URL\r\n *\r\n * @example\r\n * ```typescript\r\n * // All chaining is synchronous - single await at the end\r\n * await new Image(\"photo.jpg\")\r\n * .resize({ width: 800 })\r\n * .watermark(\"logo.png\", { gravity: \"southeast\" })\r\n * .quality(85)\r\n * .save(\"output.jpg\");\r\n * ```\r\n */\r\nexport class Image {\r\n /**\r\n * Image options that will be applied on save/export\r\n */\r\n protected options: InternalOptions = {};\r\n\r\n /**\r\n * Deferred operations pipeline\r\n */\r\n protected operations: ImageOperation[] = [];\r\n\r\n /**\r\n * Cached metadata to avoid repeated async calls\r\n */\r\n protected cachedMetadata: sharp.Metadata | null = null;\r\n\r\n /**\r\n * Whether the pipeline has been executed\r\n */\r\n protected pipelineExecuted = false;\r\n\r\n /**\r\n * Sharp image object\r\n */\r\n public readonly image: sharp.Sharp;\r\n\r\n /**\r\n * Formats that support quality option\r\n */\r\n protected static readonly QUALITY_FORMATS = [\"jpeg\", \"jpg\", \"webp\", \"avif\", \"tiff\", \"heif\"];\r\n\r\n /**\r\n * Constructor\r\n */\r\n public constructor(image: ImageInput | sharp.Sharp) {\r\n // An existing sharp instance carries its own module — short-circuit before\r\n // resolving sharp, so cloning never pays for (or fails on) a module load.\r\n if (image instanceof Object && \"clone\" in image && typeof image.clone === \"function\") {\r\n this.image = image as sharp.Sharp;\r\n } else {\r\n this.image = resolveSharp()(image as ImageInput);\r\n }\r\n }\r\n\r\n /**\r\n * Create image instance from file path\r\n */\r\n public static fromFile(path: string): Image {\r\n return new Image(path);\r\n }\r\n\r\n /**\r\n * Create image instance from buffer\r\n */\r\n public static fromBuffer(buffer: Buffer): Image {\r\n return new Image(buffer);\r\n }\r\n\r\n /**\r\n * Create image instance from url\r\n */\r\n public static async fromUrl(url: string): Promise<Image> {\r\n // SSRF-guarded: scheme allowlist, private-IP deny (incl. redirects), size cap, timeout\r\n const { buffer, ok, status, statusText } = await safeFetchToBuffer(url);\r\n\r\n if (!ok || buffer.length === 0) {\r\n throw new Error(\r\n `Failed to load image from URL \"${url}\": ${ok ? \"Empty response received\" : `${status} ${statusText}`}`,\r\n );\r\n }\r\n\r\n return new Image(buffer);\r\n }\r\n\r\n /**\r\n * Add an operation to the deferred pipeline\r\n */\r\n protected addOperation(operation: ImageOperation): this {\r\n this.operations.push(operation);\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Apply multiple transformations at once with a predefined execution order.\r\n *\r\n * This method ensures transformations are applied in a logical order:\r\n * resize → crop → rotate → flip/flop → colorspace → effects → opacity → format\r\n *\r\n * For custom ordering, use individual chained methods instead.\r\n */\r\n public apply(options: ImageTransformOptions): this {\r\n // 1. Resize first to work with correct dimensions\r\n if (options.resize) {\r\n this.resize(options.resize);\r\n }\r\n\r\n // 2. Crop after resize\r\n if (options.crop) {\r\n this.crop(options.crop);\r\n }\r\n\r\n // 3. Rotation\r\n if (options.rotate !== undefined) {\r\n this.rotate(options.rotate);\r\n }\r\n\r\n // 4. Mirror operations\r\n if (options.flip) {\r\n this.flip();\r\n }\r\n\r\n if (options.flop) {\r\n this.flop();\r\n }\r\n\r\n // 5. Color space conversion\r\n if (options.blackAndWhite || options.grayscale) {\r\n this.blackAndWhite();\r\n }\r\n\r\n // 6. Blur effect\r\n if (options.blur !== undefined) {\r\n this.blur(options.blur);\r\n }\r\n\r\n // 7. Sharpen effect\r\n if (options.sharpen) {\r\n const sharpenOptions = typeof options.sharpen === \"boolean\" ? undefined : options.sharpen;\r\n this.sharpen(sharpenOptions);\r\n }\r\n\r\n // 8. Tint color\r\n if (options.tint) {\r\n this.tint(options.tint);\r\n }\r\n\r\n // 9. Negate/invert\r\n if (options.negate) {\r\n const negateOptions = typeof options.negate === \"boolean\" ? undefined : options.negate;\r\n this.negate(negateOptions);\r\n }\r\n\r\n // 10. Trim edges\r\n if (options.trim) {\r\n const trimOptions = typeof options.trim === \"boolean\" ? undefined : options.trim;\r\n this.trim(trimOptions);\r\n }\r\n\r\n // 11. Watermarks\r\n if (options.watermark) {\r\n this.watermark(options.watermark.image, options.watermark.options);\r\n }\r\n\r\n if (options.watermarks) {\r\n this.watermarks(options.watermarks);\r\n }\r\n\r\n // 12. Opacity (applied via composite)\r\n if (options.opacity !== undefined) {\r\n this.opacity(options.opacity);\r\n }\r\n\r\n // 13. Store format/quality for deferred application\r\n if (options.format) {\r\n this.format(options.format);\r\n }\r\n\r\n if (options.quality !== undefined) {\r\n this.quality(options.quality);\r\n }\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Set image opacity (0-100)\r\n */\r\n public opacity(value: number): this {\r\n if (value < 0 || value > 100) {\r\n throw new Error(\"Opacity must be between 0 and 100\");\r\n }\r\n\r\n return this.addOperation({ type: \"opacity\", value });\r\n }\r\n\r\n /**\r\n * Convert image to black and white\r\n */\r\n public blackAndWhite(): this {\r\n return this.addOperation({ type: \"blackAndWhite\" });\r\n }\r\n\r\n /**\r\n * Alias for blackAndWhite\r\n */\r\n public grayscale(): this {\r\n return this.blackAndWhite();\r\n }\r\n\r\n /**\r\n * Get image dimensions (cached after first call)\r\n */\r\n public async dimensions(): Promise<{\r\n width: number | undefined;\r\n height: number | undefined;\r\n }> {\r\n const metadata = await this.metadata();\r\n\r\n return { width: metadata.width, height: metadata.height };\r\n }\r\n\r\n /**\r\n * Get image metadata (cached after first call)\r\n *\r\n * The metadata is cached to avoid repeated async operations.\r\n * Use `refreshMetadata()` to force a fresh fetch.\r\n */\r\n public async metadata(): Promise<sharp.Metadata> {\r\n if (!this.cachedMetadata) {\r\n this.cachedMetadata = await this.image.metadata();\r\n }\r\n\r\n return this.cachedMetadata;\r\n }\r\n\r\n /**\r\n * Force refresh of cached metadata\r\n *\r\n * Call this after transformations if you need updated metadata.\r\n */\r\n public async refreshMetadata(): Promise<sharp.Metadata> {\r\n this.cachedMetadata = await this.image.metadata();\r\n\r\n return this.cachedMetadata;\r\n }\r\n\r\n /**\r\n * Clear cached metadata\r\n */\r\n public clearMetadataCache(): this {\r\n this.cachedMetadata = null;\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Resize image\r\n */\r\n public resize(options: sharp.ResizeOptions): this {\r\n if (typeof options.width !== \"undefined\" && !options.width) {\r\n delete options.width;\r\n }\r\n\r\n if (typeof options.height !== \"undefined\" && !options.height) {\r\n delete options.height;\r\n }\r\n\r\n return this.addOperation({ type: \"resize\", options });\r\n }\r\n\r\n /**\r\n * Crop/extract a region from the image\r\n */\r\n public crop(options: sharp.Region): this {\r\n return this.addOperation({ type: \"crop\", options });\r\n }\r\n\r\n /**\r\n * Set image quality (1-100)\r\n * Quality is stored and applied when saving/exporting\r\n * based on the final format.\r\n */\r\n public quality(quality: number): this {\r\n if (quality < 1 || quality > 100) {\r\n throw new Error(\"Quality must be between 1 and 100\");\r\n }\r\n\r\n this.options.quality = quality;\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Execute the deferred pipeline - apply all stored operations\r\n */\r\n protected async executePipeline(): Promise<sharp.Sharp> {\r\n if (this.pipelineExecuted) {\r\n return this.image;\r\n }\r\n\r\n // sharp's composite() REPLACES the previous list, so every layer is\r\n // collected and applied in a single call, in operation order.\r\n const layers: sharp.OverlayOptions[] = [];\r\n\r\n for (const operation of this.operations) {\r\n await this.executeOperation(this.image, operation, layers);\r\n }\r\n\r\n if (layers.length > 0) {\r\n this.image.composite(layers);\r\n }\r\n\r\n await this.applyFormatAndQuality(this.image);\r\n\r\n this.pipelineExecuted = true;\r\n\r\n return this.image;\r\n }\r\n\r\n /**\r\n * Execute a single operation\r\n */\r\n protected async executeOperation(\r\n image: sharp.Sharp,\r\n operation: ImageOperation,\r\n layers: sharp.OverlayOptions[] = [],\r\n ): Promise<void> {\r\n switch (operation.type) {\r\n case \"resize\":\r\n image.resize(operation.options);\r\n break;\r\n\r\n case \"crop\":\r\n image.extract(operation.options);\r\n break;\r\n\r\n case \"rotate\":\r\n image.rotate(operation.angle);\r\n break;\r\n\r\n case \"flip\":\r\n image.flip();\r\n break;\r\n\r\n case \"flop\":\r\n image.flop();\r\n break;\r\n\r\n case \"blur\":\r\n image.blur(operation.sigma);\r\n break;\r\n\r\n case \"sharpen\":\r\n image.sharpen(operation.options);\r\n break;\r\n\r\n case \"blackAndWhite\":\r\n image.toColourspace(\"b-w\");\r\n break;\r\n\r\n case \"opacity\": {\r\n const alpha = Math.round((operation.value / 100) * 255);\r\n const alphaPixel = Buffer.from([255, 255, 255, alpha]);\r\n layers.push({\r\n blend: \"dest-in\",\r\n input: alphaPixel,\r\n raw: { width: 1, height: 1, channels: 4 },\r\n tile: true,\r\n });\r\n break;\r\n }\r\n\r\n case \"negate\":\r\n image.negate(operation.options);\r\n break;\r\n\r\n case \"tint\":\r\n image.tint(operation.color);\r\n break;\r\n\r\n case \"trim\":\r\n image.trim(operation.options);\r\n break;\r\n\r\n case \"watermark\": {\r\n const buffer = await this.resolveImageBuffer(operation.config.image);\r\n layers.push({\r\n input: buffer,\r\n ...operation.config.options,\r\n });\r\n break;\r\n }\r\n\r\n case \"watermarks\": {\r\n const buffers = await Promise.all(\r\n operation.configs.map((config) => this.resolveImageBuffer(config.image)),\r\n );\r\n operation.configs.forEach((config, index) => {\r\n layers.push({\r\n input: buffers[index],\r\n ...config.options,\r\n });\r\n });\r\n break;\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Resolve an image input to a buffer\r\n */\r\n protected async resolveImageBuffer(input: ImageInput | Image): Promise<Buffer> {\r\n if (input instanceof Image) {\r\n // For Image instances, get buffer without applying options (raw buffer)\r\n return input.image.toBuffer();\r\n }\r\n\r\n // For other inputs (path, buffer, etc.), create temp sharp instance\r\n const tempImage = resolveSharp()(input);\r\n\r\n return tempImage.toBuffer();\r\n }\r\n\r\n /**\r\n * Apply format and quality options.\r\n * If no format is explicitly set, preserves the original format and applies\r\n * quality appropriately based on the format type.\r\n */\r\n protected async applyFormatAndQuality(image: sharp.Sharp): Promise<void> {\r\n const { quality, format } = this.options;\r\n\r\n if (format) {\r\n // Explicit format specified\r\n const formatOptions = quality ? { quality } : undefined;\r\n image.toFormat(format, formatOptions);\r\n return;\r\n }\r\n\r\n if (quality === undefined) {\r\n // No quality or format set, nothing to apply\r\n return;\r\n }\r\n\r\n // Quality is set but no format specified - detect original format\r\n const metadata = await this.metadata();\r\n const originalFormat = metadata.format;\r\n\r\n if (!originalFormat) {\r\n // Cannot detect format, default to webp with quality\r\n image.webp({ quality });\r\n return;\r\n }\r\n\r\n // Apply quality based on original format\r\n if (Image.QUALITY_FORMATS.includes(originalFormat)) {\r\n // Format supports quality option\r\n image.toFormat(originalFormat as ImageFormat, { quality });\r\n } else if (originalFormat === \"png\") {\r\n // PNG uses compressionLevel (0-9) instead of quality\r\n // Map quality 1-100 to compressionLevel 9-0 (higher quality = lower compression)\r\n const compressionLevel = Math.round(9 - (quality / 100) * 9);\r\n image.png({ compressionLevel });\r\n } else if (originalFormat === \"gif\") {\r\n // GIF doesn't support quality, just preserve format\r\n image.gif();\r\n }\r\n // Unknown format: preserve as-is (no quality applied)\r\n }\r\n\r\n /**\r\n * Save to file\r\n */\r\n public async save(path: string): Promise<sharp.OutputInfo> {\r\n const image = await this.executePipeline();\r\n\r\n return image.toFile(path);\r\n }\r\n\r\n /**\r\n * Convert to webp and save to file\r\n */\r\n public async saveAsWebp(path: string): Promise<sharp.OutputInfo> {\r\n // Override format to webp\r\n this.options.format = \"webp\";\r\n const image = await this.executePipeline();\r\n\r\n return image.toFile(path);\r\n }\r\n\r\n /**\r\n * Change the file format\r\n */\r\n public format(format: ImageFormat): this {\r\n this.options.format = format;\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Add watermark (deferred - executed at save time)\r\n */\r\n public watermark(image: ImageInput | Image, options: sharp.OverlayOptions = {}): this {\r\n return this.addOperation({\r\n type: \"watermark\",\r\n config: { image, options },\r\n });\r\n }\r\n\r\n /**\r\n * Add multiple watermarks (deferred - executed at save time)\r\n */\r\n public watermarks(configs: WatermarkConfig[]): this {\r\n return this.addOperation({\r\n type: \"watermarks\",\r\n configs,\r\n });\r\n }\r\n\r\n /**\r\n * Rotate image\r\n */\r\n public rotate(angle: number): this {\r\n return this.addOperation({ type: \"rotate\", angle });\r\n }\r\n\r\n /**\r\n * Flip image vertically (top to bottom)\r\n */\r\n public flip(): this {\r\n return this.addOperation({ type: \"flip\" });\r\n }\r\n\r\n /**\r\n * Flop image horizontally (left to right)\r\n */\r\n public flop(): this {\r\n return this.addOperation({ type: \"flop\" });\r\n }\r\n\r\n /**\r\n * Blur image\r\n */\r\n public blur(sigma: number): this {\r\n if (sigma < 0.3) {\r\n throw new Error(\"Blur sigma must be at least 0.3\");\r\n }\r\n\r\n return this.addOperation({ type: \"blur\", sigma });\r\n }\r\n\r\n /**\r\n * Convert to base64\r\n */\r\n public async toBase64(): Promise<string> {\r\n const image = await this.executePipeline();\r\n const buffer = await image.toBuffer();\r\n\r\n return buffer.toString(\"base64\");\r\n }\r\n\r\n /**\r\n * Convert to data URL (base64 with mime type prefix)\r\n */\r\n public async toDataUrl(): Promise<string> {\r\n const metadata = await this.metadata();\r\n const format = this.options.format || metadata.format || \"png\";\r\n const mimeType = `image/${format === \"jpg\" ? \"jpeg\" : format}`;\r\n const base64 = await this.toBase64();\r\n\r\n return `data:${mimeType};base64,${base64}`;\r\n }\r\n\r\n /**\r\n * Sharpen image\r\n */\r\n public sharpen(options?: sharp.SharpenOptions): this {\r\n return this.addOperation({ type: \"sharpen\", options });\r\n }\r\n\r\n /**\r\n * Negate/invert image colors\r\n */\r\n public negate(options?: sharp.NegateOptions): this {\r\n return this.addOperation({ type: \"negate\", options });\r\n }\r\n\r\n /**\r\n * Tint image with a color\r\n */\r\n public tint(color: sharp.Color): this {\r\n return this.addOperation({ type: \"tint\", color });\r\n }\r\n\r\n /**\r\n * Trim edges from the image\r\n */\r\n public trim(options?: sharp.TrimOptions): this {\r\n return this.addOperation({ type: \"trim\", options });\r\n }\r\n\r\n /**\r\n * Convert to buffer\r\n */\r\n public async toBuffer(): Promise<Buffer> {\r\n const image = await this.executePipeline();\r\n\r\n return image.toBuffer();\r\n }\r\n\r\n /**\r\n * Clone the image for separate transformations\r\n */\r\n public clone(): Image {\r\n const clonedImage = new Image(this.image.clone());\r\n clonedImage.options = { ...this.options };\r\n clonedImage.operations = [...this.operations];\r\n clonedImage.cachedMetadata = this.cachedMetadata ? { ...this.cachedMetadata } : null;\r\n\r\n return clonedImage;\r\n }\r\n\r\n /**\r\n * Get the current stored options\r\n */\r\n public getOptions(): Readonly<InternalOptions> {\r\n return { ...this.options };\r\n }\r\n\r\n /**\r\n * Get the pending operations count\r\n */\r\n public getPendingOperationsCount(): number {\r\n return this.operations.length;\r\n }\r\n\r\n /**\r\n * Reset all stored options\r\n */\r\n public resetOptions(): this {\r\n this.options = {};\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Clear all pending operations\r\n */\r\n public clearOperations(): this {\r\n this.operations = [];\r\n this.pipelineExecuted = false;\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Reset the image to its initial state (clear operations and options)\r\n */\r\n public reset(): this {\r\n this.operations = [];\r\n this.options = {};\r\n this.pipelineExecuted = false;\r\n this.cachedMetadata = null;\r\n\r\n return this;\r\n }\r\n}\r\n"],"mappings":";;;;;;;AAYA,MAAM,6BAA6B;;;;;;;;;;;EAWjC,KAAK;;;;AAKP,IAAI,UAA+B;;;;AAKnC,IAAI,gBAAgB;;;;;;;;AASpB,IAAI,iBAA+B;AAUnC,MAAM,iBAAiB;;;;;;;;;;;AAYvB,SAAS,eAAe,OAAyB;CAC/C,IAAI,EAAE,iBAAiB,QAAQ,OAAO;CAEtC,OACG,MAAgC,SAAS,sBAC1C,MAAM,QAAQ,SAAS,4BAA4B;AAEvD;;;;;;;;;;;;;;;;;;;;AAqBA,SAAS,eAA6B;CACpC,IAAI,CAAC,eAAe;EAClB,gBAAgB;EAEhB,IAAI;GAEF,MAAM,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K,QAAQ;EACxC,YAAY,aAAa,CAAC,GAAG,KAAK,UAAU;EAC5C,YAAY,iBAAiB,KAAK,iBAAiB,EAAE,GAAG,KAAK,eAAe,IAAI;EAEhF,OAAO;CACT;;;;CAKA,AAAO,aAAwC;EAC7C,OAAO,EAAE,GAAG,KAAK,QAAQ;CAC3B;;;;CAKA,AAAO,4BAAoC;EACzC,OAAO,KAAK,WAAW;CACzB;;;;CAKA,AAAO,eAAqB;EAC1B,KAAK,UAAU,CAAC;EAEhB,OAAO;CACT;;;;CAKA,AAAO,kBAAwB;EAC7B,KAAK,aAAa,CAAC;EACnB,KAAK,mBAAmB;EAExB,OAAO;CACT;;;;CAKA,AAAO,QAAc;EACnB,KAAK,aAAa,CAAC;EACnB,KAAK,UAAU,CAAC;EAChB,KAAK,mBAAmB;EACxB,KAAK,iBAAiB;EAEtB,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"image.mjs","names":[],"sources":["../../../../../../../core/src/image/image.ts"],"sourcesContent":["import { createRequire } from \"node:module\";\nimport type sharp from \"sharp\";\nimport type { FormatEnum } from \"sharp\";\nimport { safeFetchToBuffer } from \"../storage/utils/safe-fetch\";\n\n// ============================================================\n// Lazily Resolved Sharp Module\n// ============================================================\n\n/**\n * Installation instructions for sharp\n */\nconst SHARP_INSTALL_INSTRUCTIONS = `\nImage processing requires the sharp package.\nInstall it with:\n\n warlock add image\n\nOr manually:\n\n npm install sharp\n pnpm add sharp\n yarn add sharp\n`.trim();\n\n/**\n * Cached sharp function, populated by the first `resolveSharp()` call\n */\nlet sharpFn: typeof sharp | null = null;\n\n/**\n * Whether the resolution attempt already ran (success or failure)\n */\nlet sharpResolved = false;\n\n/**\n * Why the resolution failed, when it failed for a reason other than absence.\n *\n * Cached and re-thrown on every later call: the resolution attempt runs exactly\n * once, so without this the second construction would fall through to the\n * \"not installed\" branch and report a different, wrong cause.\n */\nlet sharpLoadError: Error | null = null;\n\n/**\n * `new Error(message, { cause })` is ES2022, and this package still compiles\n * against the ES2020 lib (see #16), where `Error` is typed as taking a message\n * only. Node has supported the option since v16, so this is the type layer\n * catching up with the runtime, not a change in what the code does.\n */\ntype ErrorWithCauseConstructor = new (message: string, options: { cause: unknown }) => Error;\n\nconst ErrorWithCause = Error as ErrorWithCauseConstructor;\n\n/**\n * Whether `error` says sharp itself is absent, as opposed to present but broken.\n *\n * Both halves are load-bearing. `MODULE_NOT_FOUND` alone is not enough: a\n * dependency missing *inside* sharp raises the very same code (`Cannot find\n * module 'color'`), and treating that as absence would tell the operator to\n * install a package they already have. So the message has to name the specifier\n * `'sharp'` exactly — quoted, which is also what keeps `'sharp-cli'` and friends\n * from matching.\n */\nfunction isSharpMissing(error: unknown): boolean {\n if (!(error instanceof Error)) return false;\n\n return (\n (error as NodeJS.ErrnoException).code === \"MODULE_NOT_FOUND\" &&\n error.message.includes(\"Cannot find module 'sharp'\")\n );\n}\n\n/**\n * Resolve sharp synchronously, on first use.\n *\n * Resolution is deliberately *lazy* and *synchronous*:\n *\n * - Lazy, because a top-level require would drag sharp's native binary into\n * every `import \"@warlock.js/core\"`, including apps that never touch images.\n * - Synchronous, because the `Image` constructor is synchronous. An async\n * import kicked off at module load leaves a window in which the module is\n * neither loaded nor known to be missing, and a constructor running inside\n * that window has no correct answer to give.\n *\n * `createRequire` gives an ESM-safe `require`, and the outcome — module, absence\n * or load failure — is cached, so the resolution runs exactly once per process.\n * The failure *reason* is cached too, not just the fact of it: every call after\n * a failed load has to report the same cause as the first one.\n *\n * @throws when sharp is not installed, or is installed but cannot be loaded\n */\nfunction resolveSharp(): typeof sharp {\n if (!sharpResolved) {\n sharpResolved = true;\n\n try {\n const require = createRequire(import.meta.url);\n const module = require(\"sharp\");\n sharpFn = (module.default ?? module) as typeof sharp;\n } catch (error) {\n sharpFn = null;\n\n if (!isSharpMissing(error)) {\n // sharp is there, it just would not load — almost always a binary built\n // for another platform. Its own error names the runtime and the fix, so\n // it is inlined *and* chained: a terminal that never prints `cause`\n // must still show the text that actually helps.\n sharpLoadError = new ErrorWithCause(`Failed to load \"sharp\": ${(error as Error).message}`, {\n cause: error,\n });\n }\n }\n }\n\n if (sharpLoadError) {\n throw sharpLoadError;\n }\n\n if (!sharpFn) {\n throw new Error(`sharp is not installed.\\n\\n${SHARP_INSTALL_INSTRUCTIONS}`);\n }\n\n return sharpFn;\n}\n\n// ============================================================\n// Types\n// ============================================================\n\nexport type ImageFormat = keyof FormatEnum;\n\nexport type ImageInput = string | Buffer | Uint8Array | ArrayBuffer;\n\n/**\n * Watermark configuration for deferred execution\n */\nexport type WatermarkConfig = {\n image: ImageInput | Image;\n options: sharp.OverlayOptions;\n};\n\n/**\n * Operation descriptor for deferred pipeline execution.\n * All operations are stored and executed at save/toBuffer time.\n */\ntype ImageOperation =\n | { type: \"resize\"; options: sharp.ResizeOptions }\n | { type: \"crop\"; options: sharp.Region }\n | { type: \"rotate\"; angle: number }\n | { type: \"flip\" }\n | { type: \"flop\" }\n | { type: \"blur\"; sigma: number }\n | { type: \"sharpen\"; options?: sharp.SharpenOptions }\n | { type: \"blackAndWhite\" }\n | { type: \"opacity\"; value: number }\n | { type: \"negate\"; options?: sharp.NegateOptions }\n | { type: \"tint\"; color: sharp.Color }\n | { type: \"trim\"; options?: sharp.TrimOptions }\n | { type: \"watermark\"; config: WatermarkConfig }\n | { type: \"watermarks\"; configs: WatermarkConfig[] };\n\n/**\n * Transformation options that can be applied in batch via `apply()` method.\n *\n * **Execution Order (when using apply()):**\n * 1. resize - Resize first to work with correct dimensions\n * 2. crop - Crop after resize to extract the desired region\n * 3. rotate - Rotation after sizing\n * 4. flip/flop - Mirror operations\n * 5. blackAndWhite/grayscale - Color space conversion\n * 6. blur - Blur effect\n * 7. sharpen - Sharpen effect\n * 8. tint - Color overlay\n * 9. negate - Invert colors\n * 10. opacity - Transparency (applied via composite)\n * 11. format/quality - Applied on save/export\n */\nexport type ImageTransformOptions = {\n /**\n * Output quality (1-100), applied based on final format\n */\n quality?: number;\n /**\n * Output format (jpeg, png, webp, avif, etc.)\n */\n format?: ImageFormat;\n /**\n * Resize options\n */\n resize?: sharp.ResizeOptions;\n /**\n * Crop/extract region\n */\n crop?: sharp.Region;\n /**\n * Rotation angle in degrees\n */\n rotate?: number;\n /**\n * Flip vertically (top to bottom)\n */\n flip?: boolean;\n /**\n * Flop horizontally (left to right)\n */\n flop?: boolean;\n /**\n * Convert to black and white\n */\n blackAndWhite?: boolean;\n /**\n * Alias for blackAndWhite\n */\n grayscale?: boolean;\n /**\n * Blur sigma (must be >= 0.3)\n */\n blur?: number;\n /**\n * Sharpen options\n */\n sharpen?: sharp.SharpenOptions | boolean;\n /**\n * Tint color\n */\n tint?: sharp.Color;\n /**\n * Negate/invert colors\n */\n negate?: sharp.NegateOptions | boolean;\n /**\n * Opacity (0-100)\n */\n opacity?: number;\n /**\n * Trim options\n */\n trim?: sharp.TrimOptions | boolean;\n /**\n * Single watermark\n */\n watermark?: WatermarkConfig;\n /**\n * Multiple watermarks\n */\n watermarks?: WatermarkConfig[];\n};\n\n/**\n * Internal options stored for deferred application\n */\ntype InternalOptions = {\n quality?: number;\n format?: ImageFormat;\n};\n\n/**\n * Image manipulation class with deferred pipeline execution.\n *\n * **Important:** This class requires the `sharp` package to be installed.\n * Install it with: `warlock add image` or `npm install sharp`\n *\n * Sharp is resolved synchronously on the first construction that needs it, so\n * the constructor and all chainable methods remain synchronous, and a missing\n * sharp throws at construction rather than at some later await.\n *\n * All operations are synchronous and stored as descriptors.\n * The pipeline is executed only when calling output methods:\n * - `save()` - Save to file\n * - `toBuffer()` - Get as buffer\n * - `toBase64()` - Get as base64 string\n * - `toDataUrl()` - Get as data URL\n *\n * @example\n * ```typescript\n * // All chaining is synchronous - single await at the end\n * await new Image(\"photo.jpg\")\n * .resize({ width: 800 })\n * .watermark(\"logo.png\", { gravity: \"southeast\" })\n * .quality(85)\n * .save(\"output.jpg\");\n * ```\n */\nexport class Image {\n /**\n * Image options that will be applied on save/export\n */\n protected options: InternalOptions = {};\n\n /**\n * Deferred operations pipeline\n */\n protected operations: ImageOperation[] = [];\n\n /**\n * Cached metadata to avoid repeated async calls\n */\n protected cachedMetadata: sharp.Metadata | null = null;\n\n /**\n * Whether the pipeline has been executed\n */\n protected pipelineExecuted = false;\n\n /**\n * Sharp image object\n */\n public readonly image: sharp.Sharp;\n\n /**\n * Formats that support quality option\n */\n protected static readonly QUALITY_FORMATS = [\"jpeg\", \"jpg\", \"webp\", \"avif\", \"tiff\", \"heif\"];\n\n /**\n * Constructor\n */\n public constructor(image: ImageInput | sharp.Sharp) {\n // An existing sharp instance carries its own module — short-circuit before\n // resolving sharp, so cloning never pays for (or fails on) a module load.\n if (image instanceof Object && \"clone\" in image && typeof image.clone === \"function\") {\n this.image = image as sharp.Sharp;\n } else {\n this.image = resolveSharp()(image as ImageInput);\n }\n }\n\n /**\n * Create image instance from file path\n */\n public static fromFile(path: string): Image {\n return new Image(path);\n }\n\n /**\n * Create image instance from buffer\n */\n public static fromBuffer(buffer: Buffer): Image {\n return new Image(buffer);\n }\n\n /**\n * Create image instance from url\n */\n public static async fromUrl(url: string): Promise<Image> {\n // SSRF-guarded: scheme allowlist, private-IP deny (incl. redirects), size cap, timeout\n const { buffer, ok, status, statusText } = await safeFetchToBuffer(url);\n\n if (!ok || buffer.length === 0) {\n throw new Error(\n `Failed to load image from URL \"${url}\": ${ok ? \"Empty response received\" : `${status} ${statusText}`}`,\n );\n }\n\n return new Image(buffer);\n }\n\n /**\n * Add an operation to the deferred pipeline\n */\n protected addOperation(operation: ImageOperation): this {\n this.operations.push(operation);\n\n return this;\n }\n\n /**\n * Apply multiple transformations at once with a predefined execution order.\n *\n * This method ensures transformations are applied in a logical order:\n * resize → crop → rotate → flip/flop → colorspace → effects → opacity → format\n *\n * For custom ordering, use individual chained methods instead.\n */\n public apply(options: ImageTransformOptions): this {\n // 1. Resize first to work with correct dimensions\n if (options.resize) {\n this.resize(options.resize);\n }\n\n // 2. Crop after resize\n if (options.crop) {\n this.crop(options.crop);\n }\n\n // 3. Rotation\n if (options.rotate !== undefined) {\n this.rotate(options.rotate);\n }\n\n // 4. Mirror operations\n if (options.flip) {\n this.flip();\n }\n\n if (options.flop) {\n this.flop();\n }\n\n // 5. Color space conversion\n if (options.blackAndWhite || options.grayscale) {\n this.blackAndWhite();\n }\n\n // 6. Blur effect\n if (options.blur !== undefined) {\n this.blur(options.blur);\n }\n\n // 7. Sharpen effect\n if (options.sharpen) {\n const sharpenOptions = typeof options.sharpen === \"boolean\" ? undefined : options.sharpen;\n this.sharpen(sharpenOptions);\n }\n\n // 8. Tint color\n if (options.tint) {\n this.tint(options.tint);\n }\n\n // 9. Negate/invert\n if (options.negate) {\n const negateOptions = typeof options.negate === \"boolean\" ? undefined : options.negate;\n this.negate(negateOptions);\n }\n\n // 10. Trim edges\n if (options.trim) {\n const trimOptions = typeof options.trim === \"boolean\" ? undefined : options.trim;\n this.trim(trimOptions);\n }\n\n // 11. Watermarks\n if (options.watermark) {\n this.watermark(options.watermark.image, options.watermark.options);\n }\n\n if (options.watermarks) {\n this.watermarks(options.watermarks);\n }\n\n // 12. Opacity (applied via composite)\n if (options.opacity !== undefined) {\n this.opacity(options.opacity);\n }\n\n // 13. Store format/quality for deferred application\n if (options.format) {\n this.format(options.format);\n }\n\n if (options.quality !== undefined) {\n this.quality(options.quality);\n }\n\n return this;\n }\n\n /**\n * Set image opacity (0-100)\n */\n public opacity(value: number): this {\n if (value < 0 || value > 100) {\n throw new Error(\"Opacity must be between 0 and 100\");\n }\n\n return this.addOperation({ type: \"opacity\", value });\n }\n\n /**\n * Convert image to black and white\n */\n public blackAndWhite(): this {\n return this.addOperation({ type: \"blackAndWhite\" });\n }\n\n /**\n * Alias for blackAndWhite\n */\n public grayscale(): this {\n return this.blackAndWhite();\n }\n\n /**\n * Get image dimensions (cached after first call)\n */\n public async dimensions(): Promise<{\n width: number | undefined;\n height: number | undefined;\n }> {\n const metadata = await this.metadata();\n\n return { width: metadata.width, height: metadata.height };\n }\n\n /**\n * Get image metadata (cached after first call)\n *\n * The metadata is cached to avoid repeated async operations.\n * Use `refreshMetadata()` to force a fresh fetch.\n */\n public async metadata(): Promise<sharp.Metadata> {\n if (!this.cachedMetadata) {\n this.cachedMetadata = await this.image.metadata();\n }\n\n return this.cachedMetadata;\n }\n\n /**\n * Force refresh of cached metadata\n *\n * Call this after transformations if you need updated metadata.\n */\n public async refreshMetadata(): Promise<sharp.Metadata> {\n this.cachedMetadata = await this.image.metadata();\n\n return this.cachedMetadata;\n }\n\n /**\n * Clear cached metadata\n */\n public clearMetadataCache(): this {\n this.cachedMetadata = null;\n\n return this;\n }\n\n /**\n * Resize image\n */\n public resize(options: sharp.ResizeOptions): this {\n if (typeof options.width !== \"undefined\" && !options.width) {\n delete options.width;\n }\n\n if (typeof options.height !== \"undefined\" && !options.height) {\n delete options.height;\n }\n\n return this.addOperation({ type: \"resize\", options });\n }\n\n /**\n * Crop/extract a region from the image\n */\n public crop(options: sharp.Region): this {\n return this.addOperation({ type: \"crop\", options });\n }\n\n /**\n * Set image quality (1-100)\n * Quality is stored and applied when saving/exporting\n * based on the final format.\n */\n public quality(quality: number): this {\n if (quality < 1 || quality > 100) {\n throw new Error(\"Quality must be between 1 and 100\");\n }\n\n this.options.quality = quality;\n\n return this;\n }\n\n /**\n * Execute the deferred pipeline - apply all stored operations\n */\n protected async executePipeline(): Promise<sharp.Sharp> {\n if (this.pipelineExecuted) {\n return this.image;\n }\n\n // sharp's composite() REPLACES the previous list, so every layer is\n // collected and applied in a single call, in operation order.\n const layers: sharp.OverlayOptions[] = [];\n\n for (const operation of this.operations) {\n await this.executeOperation(this.image, operation, layers);\n }\n\n if (layers.length > 0) {\n this.image.composite(layers);\n }\n\n await this.applyFormatAndQuality(this.image);\n\n this.pipelineExecuted = true;\n\n return this.image;\n }\n\n /**\n * Execute a single operation\n */\n protected async executeOperation(\n image: sharp.Sharp,\n operation: ImageOperation,\n layers: sharp.OverlayOptions[] = [],\n ): Promise<void> {\n switch (operation.type) {\n case \"resize\":\n image.resize(operation.options);\n break;\n\n case \"crop\":\n image.extract(operation.options);\n break;\n\n case \"rotate\":\n image.rotate(operation.angle);\n break;\n\n case \"flip\":\n image.flip();\n break;\n\n case \"flop\":\n image.flop();\n break;\n\n case \"blur\":\n image.blur(operation.sigma);\n break;\n\n case \"sharpen\":\n image.sharpen(operation.options);\n break;\n\n case \"blackAndWhite\":\n image.toColourspace(\"b-w\");\n break;\n\n case \"opacity\": {\n const alpha = Math.round((operation.value / 100) * 255);\n const alphaPixel = Buffer.from([255, 255, 255, alpha]);\n layers.push({\n blend: \"dest-in\",\n input: alphaPixel,\n raw: { width: 1, height: 1, channels: 4 },\n tile: true,\n });\n break;\n }\n\n case \"negate\":\n image.negate(operation.options);\n break;\n\n case \"tint\":\n image.tint(operation.color);\n break;\n\n case \"trim\":\n image.trim(operation.options);\n break;\n\n case \"watermark\": {\n const buffer = await this.resolveImageBuffer(operation.config.image);\n layers.push({\n input: buffer,\n ...operation.config.options,\n });\n break;\n }\n\n case \"watermarks\": {\n const buffers = await Promise.all(\n operation.configs.map((config) => this.resolveImageBuffer(config.image)),\n );\n operation.configs.forEach((config, index) => {\n layers.push({\n input: buffers[index],\n ...config.options,\n });\n });\n break;\n }\n }\n }\n\n /**\n * Resolve an image input to a buffer\n */\n protected async resolveImageBuffer(input: ImageInput | Image): Promise<Buffer> {\n if (input instanceof Image) {\n // For Image instances, get buffer without applying options (raw buffer)\n return input.image.toBuffer();\n }\n\n // For other inputs (path, buffer, etc.), create temp sharp instance\n const tempImage = resolveSharp()(input);\n\n return tempImage.toBuffer();\n }\n\n /**\n * Apply format and quality options.\n * If no format is explicitly set, preserves the original format and applies\n * quality appropriately based on the format type.\n */\n protected async applyFormatAndQuality(image: sharp.Sharp): Promise<void> {\n const { quality, format } = this.options;\n\n if (format) {\n // Explicit format specified\n const formatOptions = quality ? { quality } : undefined;\n image.toFormat(format, formatOptions);\n return;\n }\n\n if (quality === undefined) {\n // No quality or format set, nothing to apply\n return;\n }\n\n // Quality is set but no format specified - detect original format\n const metadata = await this.metadata();\n const originalFormat = metadata.format;\n\n if (!originalFormat) {\n // Cannot detect format, default to webp with quality\n image.webp({ quality });\n return;\n }\n\n // Apply quality based on original format\n if (Image.QUALITY_FORMATS.includes(originalFormat)) {\n // Format supports quality option\n image.toFormat(originalFormat as ImageFormat, { quality });\n } else if (originalFormat === \"png\") {\n // PNG uses compressionLevel (0-9) instead of quality\n // Map quality 1-100 to compressionLevel 9-0 (higher quality = lower compression)\n const compressionLevel = Math.round(9 - (quality / 100) * 9);\n image.png({ compressionLevel });\n } else if (originalFormat === \"gif\") {\n // GIF doesn't support quality, just preserve format\n image.gif();\n }\n // Unknown format: preserve as-is (no quality applied)\n }\n\n /**\n * Save to file\n */\n public async save(path: string): Promise<sharp.OutputInfo> {\n const image = await this.executePipeline();\n\n return image.toFile(path);\n }\n\n /**\n * Convert to webp and save to file\n */\n public async saveAsWebp(path: string): Promise<sharp.OutputInfo> {\n // Override format to webp\n this.options.format = \"webp\";\n const image = await this.executePipeline();\n\n return image.toFile(path);\n }\n\n /**\n * Change the file format\n */\n public format(format: ImageFormat): this {\n this.options.format = format;\n\n return this;\n }\n\n /**\n * Add watermark (deferred - executed at save time)\n */\n public watermark(image: ImageInput | Image, options: sharp.OverlayOptions = {}): this {\n return this.addOperation({\n type: \"watermark\",\n config: { image, options },\n });\n }\n\n /**\n * Add multiple watermarks (deferred - executed at save time)\n */\n public watermarks(configs: WatermarkConfig[]): this {\n return this.addOperation({\n type: \"watermarks\",\n configs,\n });\n }\n\n /**\n * Rotate image\n */\n public rotate(angle: number): this {\n return this.addOperation({ type: \"rotate\", angle });\n }\n\n /**\n * Flip image vertically (top to bottom)\n */\n public flip(): this {\n return this.addOperation({ type: \"flip\" });\n }\n\n /**\n * Flop image horizontally (left to right)\n */\n public flop(): this {\n return this.addOperation({ type: \"flop\" });\n }\n\n /**\n * Blur image\n */\n public blur(sigma: number): this {\n if (sigma < 0.3) {\n throw new Error(\"Blur sigma must be at least 0.3\");\n }\n\n return this.addOperation({ type: \"blur\", sigma });\n }\n\n /**\n * Convert to base64\n */\n public async toBase64(): Promise<string> {\n const image = await this.executePipeline();\n const buffer = await image.toBuffer();\n\n return buffer.toString(\"base64\");\n }\n\n /**\n * Convert to data URL (base64 with mime type prefix)\n */\n public async toDataUrl(): Promise<string> {\n const metadata = await this.metadata();\n const format = this.options.format || metadata.format || \"png\";\n const mimeType = `image/${format === \"jpg\" ? \"jpeg\" : format}`;\n const base64 = await this.toBase64();\n\n return `data:${mimeType};base64,${base64}`;\n }\n\n /**\n * Sharpen image\n */\n public sharpen(options?: sharp.SharpenOptions): this {\n return this.addOperation({ type: \"sharpen\", options });\n }\n\n /**\n * Negate/invert image colors\n */\n public negate(options?: sharp.NegateOptions): this {\n return this.addOperation({ type: \"negate\", options });\n }\n\n /**\n * Tint image with a color\n */\n public tint(color: sharp.Color): this {\n return this.addOperation({ type: \"tint\", color });\n }\n\n /**\n * Trim edges from the image\n */\n public trim(options?: sharp.TrimOptions): this {\n return this.addOperation({ type: \"trim\", options });\n }\n\n /**\n * Convert to buffer\n */\n public async toBuffer(): Promise<Buffer> {\n const image = await this.executePipeline();\n\n return image.toBuffer();\n }\n\n /**\n * Clone the image for separate transformations\n */\n public clone(): Image {\n const clonedImage = new Image(this.image.clone());\n clonedImage.options = { ...this.options };\n clonedImage.operations = [...this.operations];\n clonedImage.cachedMetadata = this.cachedMetadata ? { ...this.cachedMetadata } : null;\n\n return clonedImage;\n }\n\n /**\n * Get the current stored options\n */\n public getOptions(): Readonly<InternalOptions> {\n return { ...this.options };\n }\n\n /**\n * Get the pending operations count\n */\n public getPendingOperationsCount(): number {\n return this.operations.length;\n }\n\n /**\n * Reset all stored options\n */\n public resetOptions(): this {\n this.options = {};\n\n return this;\n }\n\n /**\n * Clear all pending operations\n */\n public clearOperations(): this {\n this.operations = [];\n this.pipelineExecuted = false;\n\n return this;\n }\n\n /**\n * Reset the image to its initial state (clear operations and options)\n */\n public reset(): this {\n this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W;EAAQ,CAAC;CACvD;;;;CAKA,AAAO,OAAO,SAAqC;EACjD,OAAO,KAAK,aAAa;GAAE,MAAM;GAAU;EAAQ,CAAC;CACtD;;;;CAKA,AAAO,KAAK,OAA0B;EACpC,OAAO,KAAK,aAAa;GAAE,MAAM;GAAQ;EAAM,CAAC;CAClD;;;;CAKA,AAAO,KAAK,SAAmC;EAC7C,OAAO,KAAK,aAAa;GAAE,MAAM;GAAQ;EAAQ,CAAC;CACpD;;;;CAKA,MAAa,WAA4B;EAGvC,QAAO,MAFa,KAAK,gBAAgB,EAE7B,CAAC,SAAS;CACxB;;;;CAKA,AAAO,QAAe;EACpB,MAAM,cAAc,IAAI,MAAM,KAAK,MAAM,MAAM,CAAC;EAChD,YAAY,UAAU,EAAE,GAAG,KAAK,QAAQ;EACxC,YAAY,aAAa,CAAC,GAAG,KAAK,UAAU;EAC5C,YAAY,iBAAiB,KAAK,iBAAiB,EAAE,GAAG,KAAK,eAAe,IAAI;EAEhF,OAAO;CACT;;;;CAKA,AAAO,aAAwC;EAC7C,OAAO,EAAE,GAAG,KAAK,QAAQ;CAC3B;;;;CAKA,AAAO,4BAAoC;EACzC,OAAO,KAAK,WAAW;CACzB;;;;CAKA,AAAO,eAAqB;EAC1B,KAAK,UAAU,CAAC;EAEhB,OAAO;CACT;;;;CAKA,AAAO,kBAAwB;EAC7B,KAAK,aAAa,CAAC;EACnB,KAAK,mBAAmB;EAExB,OAAO;CACT;;;;CAKA,AAAO,QAAc;EACnB,KAAK,aAAa,CAAC;EACnB,KAAK,UAAU,CAAC;EAChB,KAAK,mBAAmB;EACxB,KAAK,iBAAiB;EAEtB,OAAO;CACT;AACF"}
|
package/esm/index.d.mts
CHANGED
|
@@ -59,8 +59,9 @@ import { registerHttpPlugins } from "./http/plugins.mjs";
|
|
|
59
59
|
import { assertConfiguredHttpPortIsFree, preflightConfiguredHttpPort, remedyLines, shouldPreflightHttpPort } from "./http/boot-port-preflight.mjs";
|
|
60
60
|
import { PortInUseError, assertPortIsAvailable, isPortAvailable } from "./http/port-preflight.mjs";
|
|
61
61
|
import { HttpReadyReport, getHttpReadyReport, resetHttpReadyReport, setHttpReadyReport } from "./http/ready-report.mjs";
|
|
62
|
+
import { HttpServerRebuiltListener, notifyHttpServerRebuilt, onHttpServerRebuilt } from "./http/server-rebuilt.mjs";
|
|
62
63
|
import { deriveTraceId, parseTraceparentTraceId } from "./http/tracing/trace-id.mjs";
|
|
63
|
-
import { TracingContextSource, buildTracingContext, dispatchPhase, dispatchRequestEnd, dispatchRequestStart, isTracingEnabled, resetTracingConfigForTests, resolveTracingConfig } from "./http/tracing/tracing-dispatcher.mjs";
|
|
64
|
+
import { TracingContextSource, buildTracingContext, dispatchPhase, dispatchRequestEnd, dispatchRequestStart, isTracingEnabled, registerTracingHooks, resetTracingConfigForTests, resolveTracingConfig } from "./http/tracing/tracing-dispatcher.mjs";
|
|
64
65
|
import { RequestContextStore, requestContext, useCurrentUser, useRequest, useRequestStore } from "./http/context/request-context.mjs";
|
|
65
66
|
import { requestMemo } from "./http/context/request-memo.mjs";
|
|
66
67
|
import { LocalizedObject, getLocalized } from "./utils/get-localized.mjs";
|
|
@@ -74,6 +75,7 @@ import { RouteRegistry } from "./router/route-registry.mjs";
|
|
|
74
75
|
import { Router, router } from "./router/router.mjs";
|
|
75
76
|
import { app } from "./application/app.mjs";
|
|
76
77
|
import { Environment, RuntimeStrategy, environment, setEnvironment } from "./utils/environment.mjs";
|
|
78
|
+
import { APP_ROLES, AppRole, assertSitesRequireWebRole, getRoles, getSites, hasRole, parseRoles, parseSites, resetRolesCacheForTests, servesHttp } from "./application/roles.mjs";
|
|
77
79
|
import { Application, BootContext, BootListener, BootValidator, ShutdownListener } from "./application/application.mjs";
|
|
78
80
|
import { BOOT_SIGNAL_ENV_KEY, BOOT_SIGNAL_VERSION, BootSignal, BootSignalType, isBootSignal, sendBootSignal } from "./application/boot-signal.mjs";
|
|
79
81
|
import { AppConfigurations } from "./application/application-config-types.mjs";
|
|
@@ -178,7 +180,7 @@ import { WarlockConfigManager, isUnknownTsExtensionError, warlockConfigManager }
|
|
|
178
180
|
import { env } from "@mongez/dotenv";
|
|
179
181
|
import { colors } from "@mongez/copper";
|
|
180
182
|
export * from "@mongez/localization";
|
|
181
|
-
export { $registerUseCase, $unregisterUseCase, AccessConnector, AggregateExpressionInput, AggregateExpressions, AiConnector, AllRepositoryOptions, AppConfigurations, Application, BOOT_SIGNAL_ENV_KEY, BOOT_SIGNAL_VERSION, BadRequestError, BadSchemaUseCaseError, BaseConnector, type BenchmarkChannel, type BenchmarkConfigurations, type BenchmarkErrorResult, type BenchmarkOptions, BenchmarkProfiler, type BenchmarkProfilerOptions, type BenchmarkResult, BenchmarkSnapshots, type BenchmarkSnapshotsOptions, type BenchmarkStats, type BenchmarkSuccessResult, BootContext, BootListener, BootSignal, BootSignalType, BootValidator, CLICommand, type CLICommandAction, type CLICommandOption, type CLICommandOptions, type CLICommandPreload, type CLICommandSource, CacheConnector, type CacheMiddlewareOptions, CachedRepositoryOptions, type CapturedMail, CascadeAdapter, CascadeQueryBuilder, ChunkCallback, ClosableServer, CloudDriver, CloudStorageDriverContract, CloudStorageDriverOptions, CloudStorageFileData, type CommandActionData, type ConcurrencyLimitOptions, ConfigKey, ConfigKeyRegistry, ConfigName, ConfigRegistry, ConfigSpecialHandlers, ConflictError, Connector, ConnectorBuildContext, ConnectorBuildContribution, ConnectorBuildGenerateResult, ConnectorEsbuildPatch, ConnectorLifecyclePhase, ConnectorName, ConnectorPriority, ConnectorsManager, ConsoleChannel, ContainerTypes, CookieJarUnavailableError, CookieOptions, CspConfig, CsrfOriginCheckReason, CsrfOriginVerdict, CursorPaginationOptions, CursorPaginationResult, DEFAULT_CSP_DIRECTIVES, DOSpacesDriver, DatabaseCacheDriver, type DatabaseCacheOptions, DatabaseConnector, DatabaseLog, DatabaseLogModel, DatabaseLogOptions, DecodedAccessToken, DefineResourceOptions, DeleteManyResult, DetectedImageFormat, type DevelopmentModelModuleEntry, type DevelopmentModelModuleState, type DevelopmentModelModules, EncryptionConfigurations, EncryptionPasswordConfigurations, Environment, EventSubscription, ExistsExceptCurrentIdRuleOptions, ExistsExceptCurrentUserRuleOptions, FastifyInstance, FileNamingStrategy, FileValidationOptions, FileValidator, FileVisibility, FilterFunction, FilterOperator, FilterOptions, FilterRule, FilterRules, ForbiddenError, GenerateImageVariantsOptions, GeneratedImageDescriptor, GeneratedImageVariant, GroupByFields, GroupedRoutesOptions, HealthCheck, HealthStatus, HeraldConnector, HttpConfigurations, HttpConnector, HttpContext, HttpError, HttpErrorCodes, HttpReadyReport, HttpTracingConfig, type IdempotencyOptions, Image, ImageFormat, ImageInput, ImageTransformCallback, ImageTransformConfig, ImageTransformOptions, ImageVariantDefinition, ImageVariantFit, ImageVariantOutputFormat, ImageVariantsConfigError, InvalidCspDirectiveError, type IpFilterOptions, ListOptions, LocalDriver, LocalStorageDriverOptions, LocalizedObject, LogConfigurations, LoggerConnector, MAIL_EVENTS, Mail, type MailAddress, type MailAttachment, type MailConfigurations, MailError, type MailErrorCode, type MailEvents, type MailMode, type MailOptions, type MailPriority, type MailResult, MailerConnector, type MailersConfig, type MaintenanceOptions, Middleware, MiddlewareResponse, MimeTypes, NamedApiRoute, NoopChannel, type NormalizedMail, NotAcceptableError, NotAllowedError, NotificationsConnector, PaginationMode, PaginationResult, PartialMiddleware, PartialPick, Path, PipeableReactStream, PipelineOptions, PortInUseError, PositionalHandlerSuspect, PrefixConfig, PrefixOptions, PresignedOptions, PresignedUploadOptions, PutDirectoryOptions, PutDirectoryResult, PutFromUrlOptions, PutOptions, QueryBuilderContract, Queue, R2Driver, R2StorageDriverOptions, type RateLimitOptions, RegisterConfiguredConnectorsOptions, RegisterResource, RegisteredUseCase, RepositoryAdapterContract, RepositoryConfigurations, RepositoryEvent, RepositoryManager, RepositoryOptions, RepositoryOptionsWithCursor, RepositoryOptionsWithPages, Request, RequestContextStore, RequestController, RequestControllerContract, RequestEvent, RequestHandler, RequestHandlerType, RequestHandlerValidation, RequestLocals, RequestLog, RequestMethod, RequestUserMovedError, type ResolvedCLICommandOption, ResolvedImageVariantsConfig, Resource, ResourceArraySchema, ResourceCastType, ResourceConstructor, ResourceContract, ResourceFieldBuilder, ResourceFieldBuilderDateOutputOptions, ResourceFieldConfig, ResourceMethod, ResourceNotFoundError, ResourceOutputValueCastType, ResourceSchema, ResourceSelfReference, Response, ResponseBodyValue, ResponseEvent, ResponseSSEController, ResponseSchema, ResponseStatus, ResponseStreamController, Restful, RestfulMiddleware, ReturnedResponse, Route, RouteOptions, RouteRegistry, RouteResource, Router, RouterGroupCallback, RouterStacks, RuntimeStrategy, S3Driver, type SESConfigurations, type SMTPConfigurations, SafeFetchOptions, SafeFetchResult, SaveAsOptions, SaveMode, SaveOptions, ScopedStorage, ScopedStorageContract, SeedClock, SeedContext, SeedRecordRef, SeedResult, Seeder, SeederDependencyCycleError, SeederMetadata, SendBufferOptions, SendFileOptions, ServerError, ShutdownListener, SocketAdapterFactory, SocketConnector, SocketOptions, Storage, StorageCapabilityError, StorageConfigurations, StorageConnector, StorageCopyEventPayload, StorageDriverConfig, StorageDriverContextStore, StorageDriverContract, StorageDriverName, StorageDriverRegistry, StorageDriverType, StorageError, StorageErrorOptions, StorageEventHandler, StorageEventPayload, StorageEventType, StorageFile, StorageFileData, StorageFileInfo, StorageManagerContract, StorageNotInitializedError, StoragePutEventPayload, StreamReactResponseOptions, TemporaryTokenError, TemporaryTokenPayload, TemporaryTokenValidation, TracingContext, TracingContextSource, TracingHooks, TracingPhaseInfo, TracingRequestEndInfo, Track, TrackableModel, TypedAllRepositoryOptions, TypedRepositoryOptions, TypedRepositoryOptionsWithCursor, TypedRepositoryOptionsWithPages, UPDATE_MANY_BATCH_SIZE, UPLOADS_DEFAULTS, UnAuthorizedError, UniqueExceptCurrentIdRuleOptions, UniqueExceptCurrentUserRuleOptions, UnknownSeederDependencyError, UploadedFile, UploadedFileImageOptions, UploadedFileJson, UploadedFileQuery, UploadsConfigurations, UploadsImagesConfigurations, UseCase, UseCaseAfterMiddleware, UseCaseBeforeMiddleware, UseCaseBroadcastChannel, UseCaseBroadcastEvent, UseCaseBroadcastOption, UseCaseConfigurations, UseCaseContext, UseCaseErrorResult, UseCaseEventsCallbacksMap, UseCaseGuard, UseCaseHandler, UseCaseOnExecutingContext, UseCaseResult, UseCaseRuntimeOptions, UseCaseWithSchema, ValidationConfiguration, VariantOutputFormat, VariantSourceFormat, WarlockConfig, WarlockConfigManager, WatermarkConfig, WhereOperator, XMLable, addUseCaseHistory, anyMatch, app, appLog, appPath, applyCspHeader, assertConfiguredHttpPortIsFree, assertMailCount, assertMailSent, assertNoReservedConnectorNames, assertPortIsAvailable, assertUniqueConnectorNames, assetsUrl, bootstrap, broadcastUseCaseResult, buildCspHeaderValue, buildIdempotencyCacheKey, buildTracingContext, cachePath, captureMail, clearPositionalHandlerSuspects, clearTestMailbox, closeAllMailers, closeMailer, closeServerWithTimeout, colors, command, config, configPath, configSpecialHandlers, connectorsManager, container, createHttpApplication, createRequestStore, decrypt, defaultHttpConfigurations, defineConfig, defineResource, deriveTraceId, describePositionalHandlerSuspect, dispatchPhase, dispatchRequestEnd, dispatchRequestStart, displayEnvironmentMode, encrypt, ensureFatalIsVisible, env, environment, existsExceptCurrentIdRule, existsExceptCurrentUserRule, fetchLatestVersion, fileExtensionRule, fileRule, fileTypeRule, findMailsBySubject, findMailsTo, fireLifecycleEvent, forgetPositionalHandlerSuspects, generateImageVariants, generateMailId, getDefaultMailConfig, getHttpReadyReport, getHttpServer, getLastMail, getLocalized, getMailEventName, getMailMode, getMailboxSize, getMailer, getMailerConfig, getMimeType, getPoolStats, getPublicUrl, getSocketServer, getTestMailbox, getUseCase, getUseCaseHistory, getUseCases, globalEventsCallbacksMap, globalUseCasesEvents, hashBody, hashPassword, health, hmacHash, httpConfig, imageRule, increaseUseCaseFailedCalls, increaseUseCaseSuccessCalls, inspectHandlerSignature, ipMatches, isAllowedCsrfOrigin, isBootSignal, isDevelopmentMode, isNewerVersion, isPortAvailable, isPrivateOrReservedIp, isProductionMode, isTestMode, isTracingEnabled, isUnknownTsExtensionError, isValidIdempotencyKey, listPositionalHandlerSuspects, loadS3, logResponse, logsPath, looksLikePositionalHandler, mailEvents, matchesDerivedRouteName, measure, mergeCspDirectives, middleware, normalizeOrigin, normalizeRequestPath, normalizeRoutePath, originOf, ownOrigin, parseSize, parseTraceparentTraceId, paths, preflightConfiguredHttpPort, promiseAllObject, publicPath, publicUrl, registerAppConfig, registerConfiguredConnectors, registerHttpPlugins, remedyLines, renderReact, renderReactMail, reportPositionalHandlerSuspects, requestContext, requestMemo, requiresDefaultCsrfGuard, resetHttpReadyReport, resetMailConfig, resetTracingConfigForTests, resolveCspConfig, resolveCsrfOriginVerdict, resolveMailConfig, resolveTracingConfig, resolveWithinRoot, rootPath, routeNameMethodSuffix, router, runDefaultCsrfGuard, runPipeline, safeFetchToBuffer, sanitizePath, seeder, sendBootSignal, sendMail, serializeCspDirectives, setBaseUrl, setConfig, setEnvironment, setHttpReadyReport, setLogConfigurations, setMailConfigurations, setMailMode, shouldPreflightHttpPort, sleep, sluggable, srcPath, startHttpServer, stopHttpApplication, storage, storageConfig, storageConfigurations, storageDriverContext, storagePath, streamReactResponse, t, tempPath, toJson, uniqueExceptCurrentIdRule, uniqueExceptCurrentUserRule, uploadedFileController, uploadedFileMetadataSchema, uploadsConfig, uploadsPath, uploadsUrl, url, useCase, useComputedModel, useComputedSlug, useCurrentUser, useHashedPassword, useRequest, useRequestStore, validateCspConfigAtBoot, validateCspDirectives, verifyMailer, verifyPassword, warlockConfigManager, warlockPath, wasMailSentTo, wasMailSentWithSubject, wrapResponseInDataKey };
|
|
183
|
+
export { $registerUseCase, $unregisterUseCase, APP_ROLES, AccessConnector, AggregateExpressionInput, AggregateExpressions, AiConnector, AllRepositoryOptions, AppConfigurations, AppRole, Application, BOOT_SIGNAL_ENV_KEY, BOOT_SIGNAL_VERSION, BadRequestError, BadSchemaUseCaseError, BaseConnector, type BenchmarkChannel, type BenchmarkConfigurations, type BenchmarkErrorResult, type BenchmarkOptions, BenchmarkProfiler, type BenchmarkProfilerOptions, type BenchmarkResult, BenchmarkSnapshots, type BenchmarkSnapshotsOptions, type BenchmarkStats, type BenchmarkSuccessResult, BootContext, BootListener, BootSignal, BootSignalType, BootValidator, CLICommand, type CLICommandAction, type CLICommandOption, type CLICommandOptions, type CLICommandPreload, type CLICommandSource, CacheConnector, type CacheMiddlewareOptions, CachedRepositoryOptions, type CapturedMail, CascadeAdapter, CascadeQueryBuilder, ChunkCallback, ClosableServer, CloudDriver, CloudStorageDriverContract, CloudStorageDriverOptions, CloudStorageFileData, type CommandActionData, type ConcurrencyLimitOptions, ConfigKey, ConfigKeyRegistry, ConfigName, ConfigRegistry, ConfigSpecialHandlers, ConflictError, Connector, ConnectorBuildContext, ConnectorBuildContribution, ConnectorBuildGenerateResult, ConnectorEsbuildPatch, ConnectorLifecyclePhase, ConnectorName, ConnectorPriority, ConnectorsManager, ConsoleChannel, ContainerTypes, CookieJarUnavailableError, CookieOptions, CspConfig, CsrfOriginCheckReason, CsrfOriginVerdict, CursorPaginationOptions, CursorPaginationResult, DEFAULT_CSP_DIRECTIVES, DOSpacesDriver, DatabaseCacheDriver, type DatabaseCacheOptions, DatabaseConnector, DatabaseLog, DatabaseLogModel, DatabaseLogOptions, DecodedAccessToken, DefineResourceOptions, DeleteManyResult, DetectedImageFormat, type DevelopmentModelModuleEntry, type DevelopmentModelModuleState, type DevelopmentModelModules, EncryptionConfigurations, EncryptionPasswordConfigurations, Environment, EventSubscription, ExistsExceptCurrentIdRuleOptions, ExistsExceptCurrentUserRuleOptions, FastifyInstance, FileNamingStrategy, FileValidationOptions, FileValidator, FileVisibility, FilterFunction, FilterOperator, FilterOptions, FilterRule, FilterRules, ForbiddenError, GenerateImageVariantsOptions, GeneratedImageDescriptor, GeneratedImageVariant, GroupByFields, GroupedRoutesOptions, HealthCheck, HealthStatus, HeraldConnector, HttpConfigurations, HttpConnector, HttpContext, HttpError, HttpErrorCodes, HttpReadyReport, HttpServerRebuiltListener, HttpTracingConfig, type IdempotencyOptions, Image, ImageFormat, ImageInput, ImageTransformCallback, ImageTransformConfig, ImageTransformOptions, ImageVariantDefinition, ImageVariantFit, ImageVariantOutputFormat, ImageVariantsConfigError, InvalidCspDirectiveError, type IpFilterOptions, ListOptions, LocalDriver, LocalStorageDriverOptions, LocalizedObject, LogConfigurations, LoggerConnector, MAIL_EVENTS, Mail, type MailAddress, type MailAttachment, type MailConfigurations, MailError, type MailErrorCode, type MailEvents, type MailMode, type MailOptions, type MailPriority, type MailResult, MailerConnector, type MailersConfig, type MaintenanceOptions, Middleware, MiddlewareResponse, MimeTypes, NamedApiRoute, NoopChannel, type NormalizedMail, NotAcceptableError, NotAllowedError, NotificationsConnector, PaginationMode, PaginationResult, PartialMiddleware, PartialPick, Path, PipeableReactStream, PipelineOptions, PortInUseError, PositionalHandlerSuspect, PrefixConfig, PrefixOptions, PresignedOptions, PresignedUploadOptions, PutDirectoryOptions, PutDirectoryResult, PutFromUrlOptions, PutOptions, QueryBuilderContract, Queue, R2Driver, R2StorageDriverOptions, type RateLimitOptions, RegisterConfiguredConnectorsOptions, RegisterResource, RegisteredUseCase, RepositoryAdapterContract, RepositoryConfigurations, RepositoryEvent, RepositoryManager, RepositoryOptions, RepositoryOptionsWithCursor, RepositoryOptionsWithPages, Request, RequestContextStore, RequestController, RequestControllerContract, RequestEvent, RequestHandler, RequestHandlerType, RequestHandlerValidation, RequestLocals, RequestLog, RequestMethod, RequestUserMovedError, type ResolvedCLICommandOption, ResolvedImageVariantsConfig, Resource, ResourceArraySchema, ResourceCastType, ResourceConstructor, ResourceContract, ResourceFieldBuilder, ResourceFieldBuilderDateOutputOptions, ResourceFieldConfig, ResourceMethod, ResourceNotFoundError, ResourceOutputValueCastType, ResourceSchema, ResourceSelfReference, Response, ResponseBodyValue, ResponseEvent, ResponseSSEController, ResponseSchema, ResponseStatus, ResponseStreamController, Restful, RestfulMiddleware, ReturnedResponse, Route, RouteOptions, RouteRegistry, RouteResource, Router, RouterGroupCallback, RouterStacks, RuntimeStrategy, S3Driver, type SESConfigurations, type SMTPConfigurations, SafeFetchOptions, SafeFetchResult, SaveAsOptions, SaveMode, SaveOptions, ScopedStorage, ScopedStorageContract, SeedClock, SeedContext, SeedRecordRef, SeedResult, Seeder, SeederDependencyCycleError, SeederMetadata, SendBufferOptions, SendFileOptions, ServerError, ShutdownListener, SocketAdapterFactory, SocketConnector, SocketOptions, Storage, StorageCapabilityError, StorageConfigurations, StorageConnector, StorageCopyEventPayload, StorageDriverConfig, StorageDriverContextStore, StorageDriverContract, StorageDriverName, StorageDriverRegistry, StorageDriverType, StorageError, StorageErrorOptions, StorageEventHandler, StorageEventPayload, StorageEventType, StorageFile, StorageFileData, StorageFileInfo, StorageManagerContract, StorageNotInitializedError, StoragePutEventPayload, StreamReactResponseOptions, TemporaryTokenError, TemporaryTokenPayload, TemporaryTokenValidation, TracingContext, TracingContextSource, TracingHooks, TracingPhaseInfo, TracingRequestEndInfo, Track, TrackableModel, TypedAllRepositoryOptions, TypedRepositoryOptions, TypedRepositoryOptionsWithCursor, TypedRepositoryOptionsWithPages, UPDATE_MANY_BATCH_SIZE, UPLOADS_DEFAULTS, UnAuthorizedError, UniqueExceptCurrentIdRuleOptions, UniqueExceptCurrentUserRuleOptions, UnknownSeederDependencyError, UploadedFile, UploadedFileImageOptions, UploadedFileJson, UploadedFileQuery, UploadsConfigurations, UploadsImagesConfigurations, UseCase, UseCaseAfterMiddleware, UseCaseBeforeMiddleware, UseCaseBroadcastChannel, UseCaseBroadcastEvent, UseCaseBroadcastOption, UseCaseConfigurations, UseCaseContext, UseCaseErrorResult, UseCaseEventsCallbacksMap, UseCaseGuard, UseCaseHandler, UseCaseOnExecutingContext, UseCaseResult, UseCaseRuntimeOptions, UseCaseWithSchema, ValidationConfiguration, VariantOutputFormat, VariantSourceFormat, WarlockConfig, WarlockConfigManager, WatermarkConfig, WhereOperator, XMLable, addUseCaseHistory, anyMatch, app, appLog, appPath, applyCspHeader, assertConfiguredHttpPortIsFree, assertMailCount, assertMailSent, assertNoReservedConnectorNames, assertPortIsAvailable, assertSitesRequireWebRole, assertUniqueConnectorNames, assetsUrl, bootstrap, broadcastUseCaseResult, buildCspHeaderValue, buildIdempotencyCacheKey, buildTracingContext, cachePath, captureMail, clearPositionalHandlerSuspects, clearTestMailbox, closeAllMailers, closeMailer, closeServerWithTimeout, colors, command, config, configPath, configSpecialHandlers, connectorsManager, container, createHttpApplication, createRequestStore, decrypt, defaultHttpConfigurations, defineConfig, defineResource, deriveTraceId, describePositionalHandlerSuspect, dispatchPhase, dispatchRequestEnd, dispatchRequestStart, displayEnvironmentMode, encrypt, ensureFatalIsVisible, env, environment, existsExceptCurrentIdRule, existsExceptCurrentUserRule, fetchLatestVersion, fileExtensionRule, fileRule, fileTypeRule, findMailsBySubject, findMailsTo, fireLifecycleEvent, forgetPositionalHandlerSuspects, generateImageVariants, generateMailId, getDefaultMailConfig, getHttpReadyReport, getHttpServer, getLastMail, getLocalized, getMailEventName, getMailMode, getMailboxSize, getMailer, getMailerConfig, getMimeType, getPoolStats, getPublicUrl, getRoles, getSites, getSocketServer, getTestMailbox, getUseCase, getUseCaseHistory, getUseCases, globalEventsCallbacksMap, globalUseCasesEvents, hasRole, hashBody, hashPassword, health, hmacHash, httpConfig, imageRule, increaseUseCaseFailedCalls, increaseUseCaseSuccessCalls, inspectHandlerSignature, ipMatches, isAllowedCsrfOrigin, isBootSignal, isDevelopmentMode, isNewerVersion, isPortAvailable, isPrivateOrReservedIp, isProductionMode, isTestMode, isTracingEnabled, isUnknownTsExtensionError, isValidIdempotencyKey, listPositionalHandlerSuspects, loadS3, logResponse, logsPath, looksLikePositionalHandler, mailEvents, matchesDerivedRouteName, measure, mergeCspDirectives, middleware, normalizeOrigin, normalizeRequestPath, normalizeRoutePath, notifyHttpServerRebuilt, onHttpServerRebuilt, originOf, ownOrigin, parseRoles, parseSites, parseSize, parseTraceparentTraceId, paths, preflightConfiguredHttpPort, promiseAllObject, publicPath, publicUrl, registerAppConfig, registerConfiguredConnectors, registerHttpPlugins, registerTracingHooks, remedyLines, renderReact, renderReactMail, reportPositionalHandlerSuspects, requestContext, requestMemo, requiresDefaultCsrfGuard, resetHttpReadyReport, resetMailConfig, resetRolesCacheForTests, resetTracingConfigForTests, resolveCspConfig, resolveCsrfOriginVerdict, resolveMailConfig, resolveTracingConfig, resolveWithinRoot, rootPath, routeNameMethodSuffix, router, runDefaultCsrfGuard, runPipeline, safeFetchToBuffer, sanitizePath, seeder, sendBootSignal, sendMail, serializeCspDirectives, servesHttp, setBaseUrl, setConfig, setEnvironment, setHttpReadyReport, setLogConfigurations, setMailConfigurations, setMailMode, shouldPreflightHttpPort, sleep, sluggable, srcPath, startHttpServer, stopHttpApplication, storage, storageConfig, storageConfigurations, storageDriverContext, storagePath, streamReactResponse, t, tempPath, toJson, uniqueExceptCurrentIdRule, uniqueExceptCurrentUserRule, uploadedFileController, uploadedFileMetadataSchema, uploadsConfig, uploadsPath, uploadsUrl, url, useCase, useComputedModel, useComputedSlug, useCurrentUser, useHashedPassword, useRequest, useRequestStore, validateCspConfigAtBoot, validateCspDirectives, verifyMailer, verifyPassword, warlockConfigManager, warlockPath, wasMailSentTo, wasMailSentWithSubject, wrapResponseInDataKey };
|
|
182
184
|
import "./config/types.mjs";
|
|
183
185
|
import "./http/request.mjs";
|
|
184
186
|
import "./http/types.mjs";
|
package/esm/index.mjs
CHANGED
|
@@ -26,7 +26,7 @@ import { isAllowedCsrfOrigin, normalizeOrigin, originOf, ownOrigin, resolveCsrfO
|
|
|
26
26
|
import { requiresDefaultCsrfGuard, runDefaultCsrfGuard } from "./http/csrf-default-guard.mjs";
|
|
27
27
|
import { BadRequestError, ConflictError, CookieJarUnavailableError, ForbiddenError, HttpError, NotAcceptableError, NotAllowedError, RequestUserMovedError, ResourceNotFoundError, ServerError, UnAuthorizedError } from "./http/errors/errors.mjs";
|
|
28
28
|
import { deriveTraceId, parseTraceparentTraceId } from "./http/tracing/trace-id.mjs";
|
|
29
|
-
import { buildTracingContext, dispatchPhase, dispatchRequestEnd, dispatchRequestStart, isTracingEnabled, resetTracingConfigForTests, resolveTracingConfig } from "./http/tracing/tracing-dispatcher.mjs";
|
|
29
|
+
import { buildTracingContext, dispatchPhase, dispatchRequestEnd, dispatchRequestStart, isTracingEnabled, registerTracingHooks, resetTracingConfigForTests, resolveTracingConfig } from "./http/tracing/tracing-dispatcher.mjs";
|
|
30
30
|
import { createRequestStore, t } from "./http/middleware/inject-request-context.mjs";
|
|
31
31
|
import { defaultHttpConfigurations, httpConfig } from "./http/config.mjs";
|
|
32
32
|
import { normalizeRoutePath } from "./router/normalize-route-path.mjs";
|
|
@@ -36,6 +36,7 @@ import { matchesDerivedRouteName, routeNameMethodSuffix } from "./router/route-n
|
|
|
36
36
|
import { RouteRegistry } from "./router/route-registry.mjs";
|
|
37
37
|
import { container } from "./container/index.mjs";
|
|
38
38
|
import { BOOT_SIGNAL_ENV_KEY, BOOT_SIGNAL_VERSION, isBootSignal, sendBootSignal } from "./application/boot-signal.mjs";
|
|
39
|
+
import { APP_ROLES, assertSitesRequireWebRole, getRoles, getSites, hasRole, parseRoles, parseSites, resetRolesCacheForTests, servesHttp } from "./application/roles.mjs";
|
|
39
40
|
import { Application } from "./application/application.mjs";
|
|
40
41
|
import { storageConfig, storageConfigurations } from "./storage/config.mjs";
|
|
41
42
|
import { StorageFile } from "./storage/storage-file.mjs";
|
|
@@ -85,6 +86,7 @@ import { middleware } from "./http/middleware/middleware-list.mjs";
|
|
|
85
86
|
import { PortInUseError, assertPortIsAvailable, isPortAvailable } from "./http/port-preflight.mjs";
|
|
86
87
|
import { assertConfiguredHttpPortIsFree, preflightConfiguredHttpPort, remedyLines, shouldPreflightHttpPort } from "./http/boot-port-preflight.mjs";
|
|
87
88
|
import { getHttpReadyReport, resetHttpReadyReport, setHttpReadyReport } from "./http/ready-report.mjs";
|
|
89
|
+
import { notifyHttpServerRebuilt, onHttpServerRebuilt } from "./http/server-rebuilt.mjs";
|
|
88
90
|
import { requestMemo } from "./http/context/request-memo.mjs";
|
|
89
91
|
import "./http/index.mjs";
|
|
90
92
|
import { existsExceptCurrentIdRule } from "./validation/database/exists-except-current-id.mjs";
|
|
@@ -173,4 +175,4 @@ import { colors } from "@mongez/copper";
|
|
|
173
175
|
|
|
174
176
|
export * from "@mongez/localization"
|
|
175
177
|
|
|
176
|
-
export { $registerUseCase, $unregisterUseCase, AccessConnector, AiConnector, Application, BOOT_SIGNAL_ENV_KEY, BOOT_SIGNAL_VERSION, BadRequestError, BadSchemaUseCaseError, BaseConnector, BenchmarkProfiler, BenchmarkSnapshots, CLICommand, CacheConnector, CascadeAdapter, CascadeQueryBuilder, CloudDriver, ConfigSpecialHandlers, ConflictError, ConnectorLifecyclePhase, ConnectorPriority, ConnectorsManager, ConsoleChannel, CookieJarUnavailableError, DEFAULT_CSP_DIRECTIVES, DOSpacesDriver, DatabaseCacheDriver, DatabaseConnector, DatabaseLog, DatabaseLogModel, FileValidator, ForbiddenError, HeraldConnector, HttpConnector, HttpError, HttpErrorCodes, Image, ImageVariantsConfigError, InvalidCspDirectiveError, LocalDriver, LoggerConnector, MAIL_EVENTS, Mail, MailError, MailerConnector, MimeTypes, NoopChannel, NotAcceptableError, NotAllowedError, NotificationsConnector, Path, PortInUseError, Queue, R2Driver, RegisterResource, RepositoryManager, Request, RequestController, RequestLog, RequestUserMovedError, Resource, ResourceFieldBuilder, ResourceNotFoundError, Response, ResponseStatus, Restful, RouteRegistry, Router, S3Driver, ScopedStorage, SeederDependencyCycleError, ServerError, SocketConnector, Storage, StorageCapabilityError, StorageConnector, StorageError, StorageFile, StorageNotInitializedError, UPDATE_MANY_BATCH_SIZE, UPLOADS_DEFAULTS, UnAuthorizedError, UnknownSeederDependencyError, UploadedFile, WarlockConfigManager, addUseCaseHistory, anyMatch, app, appLog, appPath, applyCspHeader, assertConfiguredHttpPortIsFree, assertMailCount, assertMailSent, assertNoReservedConnectorNames, assertPortIsAvailable, assertUniqueConnectorNames, assetsUrl, bootstrap, broadcastUseCaseResult, buildCspHeaderValue, buildIdempotencyCacheKey, buildTracingContext, cachePath, captureMail, clearPositionalHandlerSuspects, clearTestMailbox, closeAllMailers, closeMailer, closeServerWithTimeout, colors, command, config, configPath, configSpecialHandlers, connectorsManager, container, createHttpApplication, createRequestStore, decrypt, defaultHttpConfigurations, defineConfig, defineResource, deriveTraceId, describePositionalHandlerSuspect, dispatchPhase, dispatchRequestEnd, dispatchRequestStart, displayEnvironmentMode, encrypt, ensureFatalIsVisible, env, environment, existsExceptCurrentIdRule, existsExceptCurrentUserRule, fetchLatestVersion, fileExtensionRule, fileRule, fileTypeRule, findMailsBySubject, findMailsTo, fireLifecycleEvent, forgetPositionalHandlerSuspects, generateImageVariants, generateMailId, getDefaultMailConfig, getHttpReadyReport, getHttpServer, getLastMail, getLocalized, getMailEventName, getMailMode, getMailboxSize, getMailer, getMailerConfig, getMimeType, getPoolStats, getPublicUrl, getSocketServer, getTestMailbox, getUseCase, getUseCaseHistory, getUseCases, globalEventsCallbacksMap, globalUseCasesEvents, hashBody, hashPassword, health, hmacHash, httpConfig, imageRule, increaseUseCaseFailedCalls, increaseUseCaseSuccessCalls, inspectHandlerSignature, ipMatches, isAllowedCsrfOrigin, isBootSignal, isDevelopmentMode, isNewerVersion, isPortAvailable, isPrivateOrReservedIp, isProductionMode, isTestMode, isTracingEnabled, isUnknownTsExtensionError, isValidIdempotencyKey, listPositionalHandlerSuspects, loadS3, logResponse, logsPath, looksLikePositionalHandler, mailEvents, matchesDerivedRouteName, measure, mergeCspDirectives, middleware, normalizeOrigin, normalizeRequestPath, normalizeRoutePath, originOf, ownOrigin, parseSize, parseTraceparentTraceId, paths, preflightConfiguredHttpPort, promiseAllObject, publicPath, publicUrl, registerAppConfig, registerConfiguredConnectors, registerHttpPlugins, remedyLines, renderReact, renderReactMail, reportPositionalHandlerSuspects, requestContext, requestMemo, requiresDefaultCsrfGuard, resetHttpReadyReport, resetMailConfig, resetTracingConfigForTests, resolveCspConfig, resolveCsrfOriginVerdict, resolveMailConfig, resolveTracingConfig, resolveWithinRoot, rootPath, routeNameMethodSuffix, router, runDefaultCsrfGuard, runPipeline, safeFetchToBuffer, sanitizePath, seeder, sendBootSignal, sendMail, serializeCspDirectives, setBaseUrl, setConfig, setEnvironment, setHttpReadyReport, setLogConfigurations, setMailConfigurations, setMailMode, shouldPreflightHttpPort, sleep, sluggable, srcPath, startHttpServer, stopHttpApplication, storage, storageConfig, storageConfigurations, storageDriverContext, storagePath, streamReactResponse, t, tempPath, toJson, uniqueExceptCurrentIdRule, uniqueExceptCurrentUserRule, uploadedFileController, uploadedFileMetadataSchema, uploadsConfig, uploadsPath, uploadsUrl, url, useCase, useComputedModel, useComputedSlug, useCurrentUser, useHashedPassword, useRequest, useRequestStore, validateCspConfigAtBoot, validateCspDirectives, verifyMailer, verifyPassword, warlockConfigManager, warlockPath, wasMailSentTo, wasMailSentWithSubject, wrapResponseInDataKey };
|
|
178
|
+
export { $registerUseCase, $unregisterUseCase, APP_ROLES, AccessConnector, AiConnector, Application, BOOT_SIGNAL_ENV_KEY, BOOT_SIGNAL_VERSION, BadRequestError, BadSchemaUseCaseError, BaseConnector, BenchmarkProfiler, BenchmarkSnapshots, CLICommand, CacheConnector, CascadeAdapter, CascadeQueryBuilder, CloudDriver, ConfigSpecialHandlers, ConflictError, ConnectorLifecyclePhase, ConnectorPriority, ConnectorsManager, ConsoleChannel, CookieJarUnavailableError, DEFAULT_CSP_DIRECTIVES, DOSpacesDriver, DatabaseCacheDriver, DatabaseConnector, DatabaseLog, DatabaseLogModel, FileValidator, ForbiddenError, HeraldConnector, HttpConnector, HttpError, HttpErrorCodes, Image, ImageVariantsConfigError, InvalidCspDirectiveError, LocalDriver, LoggerConnector, MAIL_EVENTS, Mail, MailError, MailerConnector, MimeTypes, NoopChannel, NotAcceptableError, NotAllowedError, NotificationsConnector, Path, PortInUseError, Queue, R2Driver, RegisterResource, RepositoryManager, Request, RequestController, RequestLog, RequestUserMovedError, Resource, ResourceFieldBuilder, ResourceNotFoundError, Response, ResponseStatus, Restful, RouteRegistry, Router, S3Driver, ScopedStorage, SeederDependencyCycleError, ServerError, SocketConnector, Storage, StorageCapabilityError, StorageConnector, StorageError, StorageFile, StorageNotInitializedError, UPDATE_MANY_BATCH_SIZE, UPLOADS_DEFAULTS, UnAuthorizedError, UnknownSeederDependencyError, UploadedFile, WarlockConfigManager, addUseCaseHistory, anyMatch, app, appLog, appPath, applyCspHeader, assertConfiguredHttpPortIsFree, assertMailCount, assertMailSent, assertNoReservedConnectorNames, assertPortIsAvailable, assertSitesRequireWebRole, assertUniqueConnectorNames, assetsUrl, bootstrap, broadcastUseCaseResult, buildCspHeaderValue, buildIdempotencyCacheKey, buildTracingContext, cachePath, captureMail, clearPositionalHandlerSuspects, clearTestMailbox, closeAllMailers, closeMailer, closeServerWithTimeout, colors, command, config, configPath, configSpecialHandlers, connectorsManager, container, createHttpApplication, createRequestStore, decrypt, defaultHttpConfigurations, defineConfig, defineResource, deriveTraceId, describePositionalHandlerSuspect, dispatchPhase, dispatchRequestEnd, dispatchRequestStart, displayEnvironmentMode, encrypt, ensureFatalIsVisible, env, environment, existsExceptCurrentIdRule, existsExceptCurrentUserRule, fetchLatestVersion, fileExtensionRule, fileRule, fileTypeRule, findMailsBySubject, findMailsTo, fireLifecycleEvent, forgetPositionalHandlerSuspects, generateImageVariants, generateMailId, getDefaultMailConfig, getHttpReadyReport, getHttpServer, getLastMail, getLocalized, getMailEventName, getMailMode, getMailboxSize, getMailer, getMailerConfig, getMimeType, getPoolStats, getPublicUrl, getRoles, getSites, getSocketServer, getTestMailbox, getUseCase, getUseCaseHistory, getUseCases, globalEventsCallbacksMap, globalUseCasesEvents, hasRole, hashBody, hashPassword, health, hmacHash, httpConfig, imageRule, increaseUseCaseFailedCalls, increaseUseCaseSuccessCalls, inspectHandlerSignature, ipMatches, isAllowedCsrfOrigin, isBootSignal, isDevelopmentMode, isNewerVersion, isPortAvailable, isPrivateOrReservedIp, isProductionMode, isTestMode, isTracingEnabled, isUnknownTsExtensionError, isValidIdempotencyKey, listPositionalHandlerSuspects, loadS3, logResponse, logsPath, looksLikePositionalHandler, mailEvents, matchesDerivedRouteName, measure, mergeCspDirectives, middleware, normalizeOrigin, normalizeRequestPath, normalizeRoutePath, notifyHttpServerRebuilt, onHttpServerRebuilt, originOf, ownOrigin, parseRoles, parseSites, parseSize, parseTraceparentTraceId, paths, preflightConfiguredHttpPort, promiseAllObject, publicPath, publicUrl, registerAppConfig, registerConfiguredConnectors, registerHttpPlugins, registerTracingHooks, remedyLines, renderReact, renderReactMail, reportPositionalHandlerSuspects, requestContext, requestMemo, requiresDefaultCsrfGuard, resetHttpReadyReport, resetMailConfig, resetRolesCacheForTests, resetTracingConfigForTests, resolveCspConfig, resolveCsrfOriginVerdict, resolveMailConfig, resolveTracingConfig, resolveWithinRoot, rootPath, routeNameMethodSuffix, router, runDefaultCsrfGuard, runPipeline, safeFetchToBuffer, sanitizePath, seeder, sendBootSignal, sendMail, serializeCspDirectives, servesHttp, setBaseUrl, setConfig, setEnvironment, setHttpReadyReport, setLogConfigurations, setMailConfigurations, setMailMode, shouldPreflightHttpPort, sleep, sluggable, srcPath, startHttpServer, stopHttpApplication, storage, storageConfig, storageConfigurations, storageDriverContext, storagePath, streamReactResponse, t, tempPath, toJson, uniqueExceptCurrentIdRule, uniqueExceptCurrentUserRule, uploadedFileController, uploadedFileMetadataSchema, uploadsConfig, uploadsPath, uploadsUrl, url, useCase, useComputedModel, useComputedSlug, useCurrentUser, useHashedPassword, useRequest, useRequestStore, validateCspConfigAtBoot, validateCspDirectives, verifyMailer, verifyPassword, warlockConfigManager, warlockPath, wasMailSentTo, wasMailSentWithSubject, wrapResponseInDataKey };
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
//#region ../core/src/loader/app-module-importer.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* How the framework imports APPLICATION modules (config, routes, events, ...).
|
|
4
|
+
*
|
|
5
|
+
* Dev and start use native `import()` — one module graph, nothing to do. Under
|
|
6
|
+
* Vitest the test files run through vite-node while a native `import()` from
|
|
7
|
+
* framework code does not, so one worker would hold two copies of every app
|
|
8
|
+
* class and `instanceof` would fail. `setupTest({ importModule })` installs a
|
|
9
|
+
* hook here so app modules are imported from inside the test's own graph.
|
|
10
|
+
*
|
|
11
|
+
* The state lives on `globalThis` because the framework can be loaded twice in
|
|
12
|
+
* one worker (vite-node copy and native copy) and both must see the same hook.
|
|
13
|
+
*/
|
|
14
|
+
type AppModuleImporter = (fileUrl: string) => Promise<unknown>;
|
|
15
|
+
//#endregion
|
|
16
|
+
export { AppModuleImporter };
|
|
17
|
+
//# sourceMappingURL=app-module-importer.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"app-module-importer.d.mts","names":[],"sources":["../../../../../../../core/src/loader/app-module-importer.ts"],"mappings":";;AAYA;;;;AAA4D;;;;;;;KAAhD,iBAAA,IAAqB,OAAA,aAAoB,OAAO"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
//#region ../core/src/loader/app-module-importer.ts
|
|
2
|
+
const IMPORTER_KEY = Symbol.for("warlock.core.appModuleImporter");
|
|
3
|
+
/**
|
|
4
|
+
* Install (or clear, with `undefined`) the importer used for app modules.
|
|
5
|
+
*/
|
|
6
|
+
function setAppModuleImporter(importer) {
|
|
7
|
+
globalThis[IMPORTER_KEY] = importer;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Import an app module through the installed hook, else natively.
|
|
11
|
+
*/
|
|
12
|
+
async function importAppModule(fileUrl) {
|
|
13
|
+
const importer = globalThis[IMPORTER_KEY];
|
|
14
|
+
if (importer) return importer(fileUrl);
|
|
15
|
+
return import(fileUrl);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
//#endregion
|
|
19
|
+
export { importAppModule, setAppModuleImporter };
|
|
20
|
+
//# sourceMappingURL=app-module-importer.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"app-module-importer.mjs","names":[],"sources":["../../../../../../../core/src/loader/app-module-importer.ts"],"sourcesContent":["/**\n * How the framework imports APPLICATION modules (config, routes, events, ...).\n *\n * Dev and start use native `import()` — one module graph, nothing to do. Under\n * Vitest the test files run through vite-node while a native `import()` from\n * framework code does not, so one worker would hold two copies of every app\n * class and `instanceof` would fail. `setupTest({ importModule })` installs a\n * hook here so app modules are imported from inside the test's own graph.\n *\n * The state lives on `globalThis` because the framework can be loaded twice in\n * one worker (vite-node copy and native copy) and both must see the same hook.\n */\nexport type AppModuleImporter = (fileUrl: string) => Promise<unknown>;\n\nconst IMPORTER_KEY = Symbol.for(\"warlock.core.appModuleImporter\");\n\ntype ImporterHolder = { [IMPORTER_KEY]?: AppModuleImporter };\n\n/**\n * Install (or clear, with `undefined`) the importer used for app modules.\n */\nexport function setAppModuleImporter(importer: AppModuleImporter | undefined): void {\n (globalThis as ImporterHolder)[IMPORTER_KEY] = importer;\n}\n\n/**\n * Import an app module through the installed hook, else natively.\n */\nexport async function importAppModule(fileUrl: string): Promise<any> {\n const importer = (globalThis as ImporterHolder)[IMPORTER_KEY];\n\n if (importer) return importer(fileUrl);\n\n return import(fileUrl);\n}\n"],"mappings":";AAcA,MAAM,eAAe,OAAO,IAAI,gCAAgC;;;;AAOhE,SAAgB,qBAAqB,UAA+C;CAClF,AAAC,WAA8B,gBAAgB;AACjD;;;;AAKA,eAAsB,gBAAgB,SAA+B;CACnE,MAAM,WAAY,WAA8B;CAEhD,IAAI,UAAU,OAAO,SAAS,OAAO;CAErC,OAAO,OAAO;AAChB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"logger.mjs","names":[],"sources":["../../../../../../../core/src/logger/logger.ts"],"sourcesContent":["import type { LogChannel } from \"@warlock.js/logger\";\
|
|
1
|
+
{"version":3,"file":"logger.mjs","names":[],"sources":["../../../../../../../core/src/logger/logger.ts"],"sourcesContent":["import type { LogChannel } from \"@warlock.js/logger\";\nimport { log } from \"@warlock.js/logger\";\nimport { environment } from \"../utils\";\nimport type { LogConfigurations } from \"./types\";\n\nexport function setLogConfigurations(options: LogConfigurations) {\n // log configurations\n const channels: LogChannel[] = [];\n\n const env = environment();\n\n const envOptions = options[env as \"development\" | \"test\" | \"production\"];\n\n // the environment flag wins over the top-level flag\n const enabled = envOptions?.enabled ?? options.enabled ?? true;\n\n if (!enabled) {\n log.configure({ channels: [] });\n return;\n }\n\n const envChannels = envOptions?.channels;\n const defaultChannels = options.channels;\n\n if (defaultChannels) {\n channels.push(...defaultChannels);\n }\n\n if (envChannels) {\n channels.push(...envChannels);\n }\n\n log.configure({\n channels,\n });\n}\n"],"mappings":";;;;;AAKA,SAAgB,qBAAqB,SAA4B;CAE/D,MAAM,WAAyB,CAAC;CAIhC,MAAM,aAAa,QAFP,YAEiB;CAK7B,IAAI,EAFY,YAAY,WAAW,QAAQ,WAAW,OAE5C;EACZ,IAAI,UAAU,EAAE,UAAU,CAAC,EAAE,CAAC;EAC9B;CACF;CAEA,MAAM,cAAc,YAAY;CAChC,MAAM,kBAAkB,QAAQ;CAEhC,IAAI,iBACF,SAAS,KAAK,GAAG,eAAe;CAGlC,IAAI,aACF,SAAS,KAAK,GAAG,WAAW;CAG9B,IAAI,UAAU,EACZ,SACF,CAAC;AACH"}
|
package/esm/mail/events.d.mts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { CapturedMail } from "./types.mjs";
|
|
2
|
+
|
|
1
3
|
//#region ../core/src/mail/events.d.ts
|
|
2
4
|
/**
|
|
3
5
|
* Generate a unique mail ID for event namespacing
|
|
@@ -8,6 +10,7 @@ declare function generateMailId(): string;
|
|
|
8
10
|
*/
|
|
9
11
|
declare const MAIL_EVENTS: {
|
|
10
12
|
readonly BEFORE_SENDING: "mail.beforeSending";
|
|
13
|
+
readonly CAPTURED: "mail.captured";
|
|
11
14
|
readonly SENT: "mail.sent";
|
|
12
15
|
readonly SUCCESS: "mail.success";
|
|
13
16
|
readonly ERROR: "mail.error";
|
|
@@ -61,6 +64,10 @@ declare const mailEvents: {
|
|
|
61
64
|
* Subscribe to global mail events
|
|
62
65
|
*/
|
|
63
66
|
on: (eventName: keyof typeof MAIL_EVENTS, callback: (...args: any[]) => void) => import("@mongez/events").EventSubscription;
|
|
67
|
+
/**
|
|
68
|
+
* Subscribe to mail captured in development or test mode.
|
|
69
|
+
*/
|
|
70
|
+
onCaptured: (callback: (mail: CapturedMail) => void) => import("@mongez/events").EventSubscription;
|
|
64
71
|
/**
|
|
65
72
|
* Subscribe to beforeSending event (all mails)
|
|
66
73
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"events.d.mts","names":[],"sources":["../../../../../../../core/src/mail/events.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"events.d.mts","names":[],"sources":["../../../../../../../core/src/mail/events.ts"],"mappings":";;;;;AAOA;iBAAgB,cAAA;;;AAAc;cAOjB,WAAA;EAAA;;;;;;;;;;AAcb;;iBAAgB,gBAAA,CACd,MAAA,UACA,KAAqD;;AAAA;AAkCvD;;;;;;;;;;;;;;;;;;;;;;;;;;;cAAa,UAAA;;;;oCAIuB,WAAA,KAAW,IAAA;;;;mCAQ7B,KAAA,qDACuC,IAAA;EAkBJ;;;+BATtB,WAAA,EAAW,QAAA,MAAgB,IAAA,8CAAoB,iBAAA;EAgBF;;;0BAPlD,IAAA,EAAM,YAAA,uCAAqB,iBAAA;EAc/B;;;+BAPS,IAAA,iBAAqB,OAAA,iBAAwB,OAAA,qCAAc,iBAAA;;;;sBAOpE,IAAA,OAAW,MAAA,OAAa,KAAA,iBAAsB,OAAA,oCAAa,iBAAA;EAO7C;;;yBAAX,IAAA,OAAW,MAAA,iBAAuB,OAAA,oCAAa,iBAAA;;;;uBAOjD,IAAA,OAAW,KAAA,iBAAsB,OAAA,oCAAa,iBAAA;;;;wCAUnD,QAAA,GACH,IAAA,iBAAqB,OAAA,iBAAwB,OAAA,qCAAc,iBAAA;EAA3D;;;+BASG,QAAA,GACH,IAAA,OAAW,MAAA,OAAa,KAAA,iBAAsB,OAAA,oCAAa,iBAAA;EAVA;;;kCAkB1C,QAAA,GAAa,IAAA,OAAW,MAAA,iBAAuB,OAAA,oCAAa,iBAAA;EARlE;;;gCAeI,QAAA,GAAa,IAAA,OAAW,KAAA,iBAAsB,OAAA,oCAAa,iBAAA;AAAA"}
|
package/esm/mail/events.mjs
CHANGED
|
@@ -13,6 +13,7 @@ function generateMailId() {
|
|
|
13
13
|
*/
|
|
14
14
|
const MAIL_EVENTS = {
|
|
15
15
|
BEFORE_SENDING: "mail.beforeSending",
|
|
16
|
+
CAPTURED: "mail.captured",
|
|
16
17
|
SENT: "mail.sent",
|
|
17
18
|
SUCCESS: "mail.success",
|
|
18
19
|
ERROR: "mail.error"
|
|
@@ -75,6 +76,12 @@ const mailEvents = {
|
|
|
75
76
|
return events.subscribe(MAIL_EVENTS[eventName], callback);
|
|
76
77
|
},
|
|
77
78
|
/**
|
|
79
|
+
* Subscribe to mail captured in development or test mode.
|
|
80
|
+
*/
|
|
81
|
+
onCaptured: (callback) => {
|
|
82
|
+
return events.subscribe(MAIL_EVENTS.CAPTURED, callback);
|
|
83
|
+
},
|
|
84
|
+
/**
|
|
78
85
|
* Subscribe to beforeSending event (all mails)
|
|
79
86
|
*/
|
|
80
87
|
onBeforeSending: (callback) => {
|
package/esm/mail/events.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"events.mjs","names":[],"sources":["../../../../../../../core/src/mail/events.ts"],"sourcesContent":["import events from \"@mongez/events\";\nimport { Random } from \"@mongez/reinforcements\";\n\n/**\n * Generate a unique mail ID for event namespacing\n */\nexport function generateMailId(): string {\n return \"M\" + Random.int(32);\n}\n\n/**\n * Mail event names (global events)\n */\nexport const MAIL_EVENTS = {\n BEFORE_SENDING: \"mail.beforeSending\",\n SENT: \"mail.sent\",\n SUCCESS: \"mail.success\",\n ERROR: \"mail.error\",\n} as const;\n\n/**\n * Get namespaced event name for a specific mail\n * @param mailId Unique mail identifier\n * @param event Event type\n * @returns Namespaced event name (e.g., \"mail.abc123.success\")\n */\nexport function getMailEventName(\n mailId: string,\n event: \"beforeSending\" | \"sent\" | \"success\" | \"error\",\n): string {\n return `mail.${mailId}.${event}`;\n}\n\n/**\n * Mail events wrapper\n *\n * Supports two event patterns:\n * 1. Global events: `mail.success` - fires for ALL emails\n * 2. Specific events: `mail.$mailId.success` - fires for ONE email\n *\n * ## Usage\n *\n * ```typescript\n * // Global listener - all emails\n * mailEvents.onSuccess((mail, result) => {\n * console.log(\"Any mail sent:\", result.messageId);\n * });\n *\n * // Specific listener - one email by ID\n * const mailId = generateMailId();\n * mailEvents.onMailSuccess(mailId, (mail, result) => {\n * console.log(\"This specific mail sent:\", result.messageId);\n * });\n *\n * await sendMail({\n * id: mailId, // Use the same ID\n * to: \"user@example.com\",\n * subject: \"Hello\",\n * html: \"<p>World</p>\",\n * });\n * ```\n */\nexport const mailEvents = {\n /**\n * Trigger a global mail event\n */\n trigger: (eventName: keyof typeof MAIL_EVENTS, ...args: any[]) => {\n return events.trigger(MAIL_EVENTS[eventName], ...args);\n },\n\n /**\n * Trigger a specific mail event (by mail ID)\n */\n triggerForMail: (\n mailId: string,\n event: \"beforeSending\" | \"sent\" | \"success\" | \"error\",\n ...args: any[]\n ) => {\n return events.trigger(getMailEventName(mailId, event), ...args);\n },\n\n /**\n * Subscribe to global mail events\n */\n on: (eventName: keyof typeof MAIL_EVENTS, callback: (...args: any[]) => void) => {\n return events.subscribe(MAIL_EVENTS[eventName], callback);\n },\n\n // === GLOBAL EVENT HELPERS ===\n\n /**\n * Subscribe to beforeSending event (all mails)\n */\n onBeforeSending: (callback: (mail: any) => void | Promise<void> | false | Promise<false>) => {\n return events.subscribe(MAIL_EVENTS.BEFORE_SENDING, callback);\n },\n\n /**\n * Subscribe to sent event (all mails, after attempt)\n */\n onSent: (callback: (mail: any, result: any, error: any) => void | Promise<void>) => {\n return events.subscribe(MAIL_EVENTS.SENT, callback);\n },\n\n /**\n * Subscribe to success event (all mails)\n */\n onSuccess: (callback: (mail: any, result: any) => void | Promise<void>) => {\n return events.subscribe(MAIL_EVENTS.SUCCESS, callback);\n },\n\n /**\n * Subscribe to error event (all mails)\n */\n onError: (callback: (mail: any, error: any) => void | Promise<void>) => {\n return events.subscribe(MAIL_EVENTS.ERROR, callback);\n },\n\n // === SPECIFIC MAIL EVENT HELPERS ===\n\n /**\n * Subscribe to beforeSending event for a specific mail\n */\n onMailBeforeSending: (\n mailId: string,\n callback: (mail: any) => void | Promise<void> | false | Promise<false>,\n ) => {\n return events.subscribe(getMailEventName(mailId, \"beforeSending\"), callback);\n },\n\n /**\n * Subscribe to sent event for a specific mail\n */\n onMailSent: (\n mailId: string,\n callback: (mail: any, result: any, error: any) => void | Promise<void>,\n ) => {\n return events.subscribe(getMailEventName(mailId, \"sent\"), callback);\n },\n\n /**\n * Subscribe to success event for a specific mail\n */\n onMailSuccess: (mailId: string, callback: (mail: any, result: any) => void | Promise<void>) => {\n return events.subscribe(getMailEventName(mailId, \"success\"), callback);\n },\n\n /**\n * Subscribe to error event for a specific mail\n */\n onMailError: (mailId: string, callback: (mail: any, error: any) => void | Promise<void>) => {\n return events.subscribe(getMailEventName(mailId, \"error\"), callback);\n },\n};\n"],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"file":"events.mjs","names":[],"sources":["../../../../../../../core/src/mail/events.ts"],"sourcesContent":["import events from \"@mongez/events\";\nimport { Random } from \"@mongez/reinforcements\";\nimport type { CapturedMail } from \"./types\";\n\n/**\n * Generate a unique mail ID for event namespacing\n */\nexport function generateMailId(): string {\n return \"M\" + Random.int(32);\n}\n\n/**\n * Mail event names (global events)\n */\nexport const MAIL_EVENTS = {\n BEFORE_SENDING: \"mail.beforeSending\",\n CAPTURED: \"mail.captured\",\n SENT: \"mail.sent\",\n SUCCESS: \"mail.success\",\n ERROR: \"mail.error\",\n} as const;\n\n/**\n * Get namespaced event name for a specific mail\n * @param mailId Unique mail identifier\n * @param event Event type\n * @returns Namespaced event name (e.g., \"mail.abc123.success\")\n */\nexport function getMailEventName(\n mailId: string,\n event: \"beforeSending\" | \"sent\" | \"success\" | \"error\",\n): string {\n return `mail.${mailId}.${event}`;\n}\n\n/**\n * Mail events wrapper\n *\n * Supports two event patterns:\n * 1. Global events: `mail.success` - fires for ALL emails\n * 2. Specific events: `mail.$mailId.success` - fires for ONE email\n *\n * ## Usage\n *\n * ```typescript\n * // Global listener - all emails\n * mailEvents.onSuccess((mail, result) => {\n * console.log(\"Any mail sent:\", result.messageId);\n * });\n *\n * // Specific listener - one email by ID\n * const mailId = generateMailId();\n * mailEvents.onMailSuccess(mailId, (mail, result) => {\n * console.log(\"This specific mail sent:\", result.messageId);\n * });\n *\n * await sendMail({\n * id: mailId, // Use the same ID\n * to: \"user@example.com\",\n * subject: \"Hello\",\n * html: \"<p>World</p>\",\n * });\n * ```\n */\nexport const mailEvents = {\n /**\n * Trigger a global mail event\n */\n trigger: (eventName: keyof typeof MAIL_EVENTS, ...args: any[]) => {\n return events.trigger(MAIL_EVENTS[eventName], ...args);\n },\n\n /**\n * Trigger a specific mail event (by mail ID)\n */\n triggerForMail: (\n mailId: string,\n event: \"beforeSending\" | \"sent\" | \"success\" | \"error\",\n ...args: any[]\n ) => {\n return events.trigger(getMailEventName(mailId, event), ...args);\n },\n\n /**\n * Subscribe to global mail events\n */\n on: (eventName: keyof typeof MAIL_EVENTS, callback: (...args: any[]) => void) => {\n return events.subscribe(MAIL_EVENTS[eventName], callback);\n },\n\n // === GLOBAL EVENT HELPERS ===\n\n /**\n * Subscribe to mail captured in development or test mode.\n */\n onCaptured: (callback: (mail: CapturedMail) => void) => {\n return events.subscribe(MAIL_EVENTS.CAPTURED, callback);\n },\n\n /**\n * Subscribe to beforeSending event (all mails)\n */\n onBeforeSending: (callback: (mail: any) => void | Promise<void> | false | Promise<false>) => {\n return events.subscribe(MAIL_EVENTS.BEFORE_SENDING, callback);\n },\n\n /**\n * Subscribe to sent event (all mails, after attempt)\n */\n onSent: (callback: (mail: any, result: any, error: any) => void | Promise<void>) => {\n return events.subscribe(MAIL_EVENTS.SENT, callback);\n },\n\n /**\n * Subscribe to success event (all mails)\n */\n onSuccess: (callback: (mail: any, result: any) => void | Promise<void>) => {\n return events.subscribe(MAIL_EVENTS.SUCCESS, callback);\n },\n\n /**\n * Subscribe to error event (all mails)\n */\n onError: (callback: (mail: any, error: any) => void | Promise<void>) => {\n return events.subscribe(MAIL_EVENTS.ERROR, callback);\n },\n\n // === SPECIFIC MAIL EVENT HELPERS ===\n\n /**\n * Subscribe to beforeSending event for a specific mail\n */\n onMailBeforeSending: (\n mailId: string,\n callback: (mail: any) => void | Promise<void> | false | Promise<false>,\n ) => {\n return events.subscribe(getMailEventName(mailId, \"beforeSending\"), callback);\n },\n\n /**\n * Subscribe to sent event for a specific mail\n */\n onMailSent: (\n mailId: string,\n callback: (mail: any, result: any, error: any) => void | Promise<void>,\n ) => {\n return events.subscribe(getMailEventName(mailId, \"sent\"), callback);\n },\n\n /**\n * Subscribe to success event for a specific mail\n */\n onMailSuccess: (mailId: string, callback: (mail: any, result: any) => void | Promise<void>) => {\n return events.subscribe(getMailEventName(mailId, \"success\"), callback);\n },\n\n /**\n * Subscribe to error event for a specific mail\n */\n onMailError: (mailId: string, callback: (mail: any, error: any) => void | Promise<void>) => {\n return events.subscribe(getMailEventName(mailId, \"error\"), callback);\n },\n};\n"],"mappings":";;;;;;;AAOA,SAAgB,iBAAyB;CACvC,OAAO,MAAM,OAAO,IAAI,EAAE;AAC5B;;;;AAKA,MAAa,cAAc;CACzB,gBAAgB;CAChB,UAAU;CACV,MAAM;CACN,SAAS;CACT,OAAO;AACT;;;;;;;AAQA,SAAgB,iBACd,QACA,OACQ;CACR,OAAO,QAAQ,OAAO,GAAG;AAC3B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,MAAa,aAAa;;;;CAIxB,UAAU,WAAqC,GAAG,SAAgB;EAChE,OAAO,OAAO,QAAQ,YAAY,YAAY,GAAG,IAAI;CACvD;;;;CAKA,iBACE,QACA,OACA,GAAG,SACA;EACH,OAAO,OAAO,QAAQ,iBAAiB,QAAQ,KAAK,GAAG,GAAG,IAAI;CAChE;;;;CAKA,KAAK,WAAqC,aAAuC;EAC/E,OAAO,OAAO,UAAU,YAAY,YAAY,QAAQ;CAC1D;;;;CAOA,aAAa,aAA2C;EACtD,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ;CACxD;;;;CAKA,kBAAkB,aAA2E;EAC3F,OAAO,OAAO,UAAU,YAAY,gBAAgB,QAAQ;CAC9D;;;;CAKA,SAAS,aAA2E;EAClF,OAAO,OAAO,UAAU,YAAY,MAAM,QAAQ;CACpD;;;;CAKA,YAAY,aAA+D;EACzE,OAAO,OAAO,UAAU,YAAY,SAAS,QAAQ;CACvD;;;;CAKA,UAAU,aAA8D;EACtE,OAAO,OAAO,UAAU,YAAY,OAAO,QAAQ;CACrD;;;;CAOA,sBACE,QACA,aACG;EACH,OAAO,OAAO,UAAU,iBAAiB,QAAQ,eAAe,GAAG,QAAQ;CAC7E;;;;CAKA,aACE,QACA,aACG;EACH,OAAO,OAAO,UAAU,iBAAiB,QAAQ,MAAM,GAAG,QAAQ;CACpE;;;;CAKA,gBAAgB,QAAgB,aAA+D;EAC7F,OAAO,OAAO,UAAU,iBAAiB,QAAQ,SAAS,GAAG,QAAQ;CACvE;;;;CAKA,cAAc,QAAgB,aAA8D;EAC1F,OAAO,OAAO,UAAU,iBAAiB,QAAQ,OAAO,GAAG,QAAQ;CACrE;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"send-mail.d.mts","names":[],"sources":["../../../../../../../core/src/mail/send-mail.ts"],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"send-mail.d.mts","names":[],"sources":["../../../../../../../core/src/mail/send-mail.ts"],"mappings":";;;;;AAuRA;;;;;;;;;;;;;AAAwE;;;;;;;;;;;;;;;iBAAlD,QAAA,CAAS,OAAA,EAAS,WAAA,GAAc,OAAA,CAAQ,UAAA"}
|
package/esm/mail/send-mail.mjs
CHANGED
|
@@ -154,6 +154,17 @@ async function triggerEvents(mailId, event, ...args) {
|
|
|
154
154
|
}
|
|
155
155
|
}
|
|
156
156
|
/**
|
|
157
|
+
* Notify development and test tooling of a captured mail without allowing a
|
|
158
|
+
* synchronous listener failure to interrupt delivery.
|
|
159
|
+
*/
|
|
160
|
+
function triggerCapturedMail(captured) {
|
|
161
|
+
try {
|
|
162
|
+
mailEvents.trigger("CAPTURED", captured);
|
|
163
|
+
} catch (error) {
|
|
164
|
+
log.error("mail", "event", `Captured mail event handler error: ${error}`);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
157
168
|
* Send an email
|
|
158
169
|
*
|
|
159
170
|
* @param options Mail options including recipients, content, and configuration
|
|
@@ -215,12 +226,15 @@ async function sendMail(options) {
|
|
|
215
226
|
rejected: [],
|
|
216
227
|
response: "Test mode - mail captured"
|
|
217
228
|
};
|
|
218
|
-
|
|
229
|
+
const captured = {
|
|
230
|
+
id: mailId,
|
|
219
231
|
options,
|
|
220
232
|
normalized,
|
|
221
233
|
timestamp: /* @__PURE__ */ new Date(),
|
|
222
234
|
result
|
|
223
|
-
}
|
|
235
|
+
};
|
|
236
|
+
captureMail(captured);
|
|
237
|
+
triggerCapturedMail(captured);
|
|
224
238
|
await runMailEvent(options.onSuccess, options, result);
|
|
225
239
|
await triggerEvents(mailId, "success", options, result);
|
|
226
240
|
await runMailEvent(options.onSent, options, result, null);
|
|
@@ -238,6 +252,13 @@ async function sendMail(options) {
|
|
|
238
252
|
rejected: [],
|
|
239
253
|
response: "Development mode - mail logged"
|
|
240
254
|
};
|
|
255
|
+
triggerCapturedMail({
|
|
256
|
+
id: mailId,
|
|
257
|
+
options,
|
|
258
|
+
normalized,
|
|
259
|
+
timestamp: /* @__PURE__ */ new Date(),
|
|
260
|
+
result
|
|
261
|
+
});
|
|
241
262
|
await runMailEvent(options.onSuccess, options, result);
|
|
242
263
|
await triggerEvents(mailId, "success", options, result);
|
|
243
264
|
await runMailEvent(options.onSent, options, result, null);
|