franchising 0.5.1 → 0.7.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/dist/cli/template-assets/api/src/main.ts +13 -11
- package/dist/cli/template-assets/api/src/modules/health/controller.ts +25 -4
- package/dist/cli/template-assets/api/src/shared/http/errors.ts +17 -0
- package/dist/cli/template-assets/cloudflare/cache.service.ts +1 -0
- package/dist/cli/template-assets/cloudflare/queue.service.ts +1 -0
- package/dist/cli/template-assets/cloudflare/worker.ts +4 -0
- package/dist/cli/template-assets/github/PULL_REQUEST_TEMPLATE.md +37 -0
- package/dist/cli/template-assets/observability/adapters.ts +37 -0
- package/dist/cli/template-assets/observability/bootstrap.ts +48 -0
- package/dist/cli/template-assets/observability/env.ts +21 -0
- package/dist/cli/template-assets/observability/index.ts +10 -0
- package/dist/cli/template-assets/observability/lifecycle.ts +97 -0
- package/dist/cli/template-assets/observability/local-index.ts +9 -0
- package/dist/cli/template-assets/observability/register.ts +12 -0
- package/dist/cli/template-assets/packages/jobs/src/index.ts +4 -40
- package/dist/cli/template-assets/packages/jobs/src/shared/queue/job-id.ts +9 -0
- package/dist/cli/template-assets/packages/jobs/src/shared/queue/options.ts +7 -0
- package/dist/cli/template-assets/packages/jobs/src/shared/queue/prefix.ts +18 -0
- package/dist/cli/template-assets/packages/queue/src/index.ts +4 -0
- package/dist/cli/template-assets/packages/queue/src/shared/errors/failure-reason.ts +7 -0
- package/dist/cli/template-assets/packages/{queue-runtime/src/index.ts → queue/src/shared/redis/connection.ts} +2 -15
- package/dist/cli/template-assets/packages/queue/src/types/redis/connection.ts +6 -0
- package/dist/cli/template-assets/packages/webhooks/src/index.ts +11 -0
- package/dist/cli/template-assets/packages/webhooks/src/shared/crypto/secret.ts +81 -0
- package/dist/cli/template-assets/packages/webhooks/src/shared/signing/headers.ts +43 -0
- package/dist/cli/template-assets/packages/webhooks/src/shared/url/deliverable.ts +58 -0
- package/dist/cli/template-assets/packages/webhooks/src/types/webhooks/job.ts +18 -0
- package/dist/cli/template-assets/packages/webhooks/test/webhooks.test.ts.tpl +69 -0
- package/dist/cli/template-assets/root/dot-dockerignore +88 -8
- package/dist/cli/template-assets/root/dot-oxlintrc.json +22 -0
- package/dist/cli/template-assets/root/lefthook.yml +32 -8
- package/dist/cli/template-assets/web/src/app/(app)/layout.tsx +2 -3
- package/dist/cli/template-assets/web/src/app/(auth)/login/page.tsx +1 -1
- package/dist/cli/template-assets/web/src/app/page.tsx +1 -0
- package/dist/cli/template-assets/web/src/{lib/api-client.ts → shared/api/client.ts} +11 -8
- package/dist/cli/template-assets/web/src/{lib/server-auth.ts → shared/auth/server.ts} +1 -2
- package/dist/cli/template-assets/web/src/types/api.ts +0 -15
- package/dist/cli/template-assets/webhooks/api/src/modules/webhooks/controller.ts +81 -0
- package/dist/cli/template-assets/webhooks/api/src/modules/webhooks/dto/create-endpoint.dto.ts +25 -0
- package/dist/cli/template-assets/webhooks/api/src/modules/webhooks/dto/endpoint.dto.ts +28 -0
- package/dist/cli/template-assets/webhooks/api/src/modules/webhooks/module.ts +27 -0
- package/dist/cli/template-assets/webhooks/api/src/modules/webhooks/repository.ts +147 -0
- package/dist/cli/template-assets/webhooks/api/src/modules/webhooks/service.ts +119 -0
- package/dist/cli/template-assets/webhooks/api/src/types/webhooks/endpoint.ts +26 -0
- package/dist/cli/template-assets/webhooks/worker/src/env.ts +18 -0
- package/dist/cli/template-assets/webhooks/worker/src/modules/queue/dispatcher.ts +119 -0
- package/dist/cli/template-assets/webhooks/worker/src/modules/queue/module.ts +16 -0
- package/dist/cli/template-assets/webhooks/worker/src/modules/queue/processor.ts +176 -0
- package/dist/cli/template-assets/webhooks/worker/src/modules/queue/repository.ts +187 -0
- package/dist/cli/template-assets/webhooks/worker/src/shared/http/deliver.ts +41 -0
- package/dist/cli/template-assets/webhooks/worker/src/types/webhooks/dispatch.ts +26 -0
- package/dist/cli/template-assets/worker/src/app.module.ts +14 -0
- package/dist/cli/template-assets/worker/src/main.ts +24 -0
- package/dist/cli/template-assets/worker/src/modules/queue/processor.ts +26 -3
- package/dist/cli/template-assets/worker/src/modules/queue/retry.ts +22 -7
- package/dist/cli/template-assets/worker/test/retry.test.ts.tpl +13 -1
- package/dist/cli/template-assets/worker-messaging/messaging-api-service.ts +6 -6
- package/dist/cli/template-assets/worker-messaging/src/env.ts +1 -1
- package/dist/cli/template-assets/worker-messaging/src/modules/messaging/service.ts +2 -4
- package/dist/cli/template-assets/worker-messaging/src/modules/queue/module.ts +1 -1
- package/dist/cli/template-assets/worker-messaging/src/modules/queue/processor.ts +32 -10
- package/dist/cli.js +631 -314
- package/dist/{index-BDYdEWl2.d.ts → index-B_byXBRW.d.cts} +10 -2
- package/dist/{index-BDYdEWl2.d.cts → index-B_byXBRW.d.ts} +10 -2
- package/dist/{index-u3ArUXO0.d.ts → index-CNlb6WNr.d.ts} +2 -2
- package/dist/{index--EJQTnHy.d.cts → index-I_Nx5SsQ.d.cts} +2 -2
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/messaging/index.cjs +1 -1
- package/dist/messaging/index.d.cts +1 -1
- package/dist/messaging/index.d.ts +1 -1
- package/dist/messaging/index.js +1 -1
- package/dist/sso/client.d.cts +7 -2
- package/dist/sso/client.d.ts +7 -2
- package/dist/sso/index.cjs +3 -1
- package/dist/sso/index.cjs.map +1 -1
- package/dist/sso/index.d.cts +1 -1
- package/dist/sso/index.d.ts +1 -1
- package/dist/sso/index.js +3 -1
- package/dist/sso/index.js.map +1 -1
- package/dist/sso/nestjs.d.cts +2 -2
- package/dist/sso/nestjs.d.ts +2 -2
- package/dist/sso/resource.d.cts +2 -2
- package/dist/sso/resource.d.ts +2 -2
- package/dist/version-Cm1EJ-YK.js +1 -0
- package/dist/{version-CrBclf1K.cjs → version-iERj9NJ6.cjs} +1 -1
- package/package.json +1 -1
- package/dist/cli/template-assets/api/src/errors/codes.ts +0 -17
- package/dist/cli/template-assets/api/src/errors/index.ts +0 -16
- package/dist/cli/template-assets/api/src/filters/exception.ts +0 -53
- package/dist/cli/template-assets/api/src/shared/exceptions.ts +0 -40
- package/dist/cli/template-assets/api/src/shared/response.ts +0 -31
- package/dist/cli/template-assets/api/src/telemetry.ts +0 -59
- package/dist/version-BhZpPjUh.js +0 -1
- /package/dist/cli/template-assets/web/src/{lib/auth-client.ts → shared/auth/client.ts} +0 -0
package/dist/cli.js
CHANGED
|
@@ -1,112 +1,112 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a as e,i as t,o as n,r}from"./skills-C1uwr9Pp.js";import{EventEmitter as i}from"node:events";import a,{spawn as o}from"node:child_process";import
|
|
3
|
-
`)}displayWidth(e){return
|
|
2
|
+
import{a as e,i as t,o as n,r}from"./skills-C1uwr9Pp.js";import{EventEmitter as i}from"node:events";import a,{spawn as o,spawnSync as s}from"node:child_process";import c from"node:path";import l,{existsSync as u,readFileSync as d}from"node:fs";import f,{stdin as p,stdout as m}from"node:process";import{stripVTControlCharacters as h,styleText as g}from"node:util";import _,*as v from"node:readline";import{ReadStream as y}from"node:tty";import{access as b,copyFile as x,mkdir as S,mkdtemp as ee,readFile as C,readdir as te,rm as ne,symlink as re,writeFile as ie}from"node:fs/promises";import{fileURLToPath as ae}from"node:url";import{randomBytes as oe}from"node:crypto";import{homedir as se,tmpdir as ce}from"node:os";var le=Object.create,ue=Object.defineProperty,de=Object.getOwnPropertyDescriptor,fe=Object.getOwnPropertyNames,pe=Object.getPrototypeOf,me=Object.prototype.hasOwnProperty,he=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t,t.exports),e=null),t.exports),ge=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=fe(t),a=0,o=i.length,s;a<o;a++)s=i[a],!me.call(e,s)&&s!==n&&ue(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=de(t,s))||r.enumerable});return e},_e=(e,t,n)=>(n=e==null?{}:le(pe(e)),ge(t||!e||!e.__esModule||!me.call(e,`default`)?ue(n,`default`,{value:e,enumerable:!0}):n,e)),ve=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},ye=class extends ve{constructor(e){super(1,`commander.invalidArgument`,e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}},be=class{constructor(e,t){switch(this.description=t||``,this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case`<`:this.required=!0,this._name=e.slice(1,-1);break;case`[`:this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e}this._name.endsWith(`...`)&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,t)=>{if(!this.argChoices.includes(e))throw new ye(`Allowed choices are ${this.argChoices.join(`, `)}.`);return this.variadic?this._collectValue(e,t):e},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function xe(e){let t=e.name()+(e.variadic===!0?`...`:``);return e.required?`<`+t+`>`:`[`+t+`]`}var Se=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter(e=>!e._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((e,t)=>e.name().localeCompare(t.name())),t}compareOptions(e,t){let n=e=>e.short?e.short.replace(/^-/,``):e.long.replace(/^--/,``);return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter(e=>!e.hidden),n=e._getHelpOption();if(n&&!n.hidden){let r=n.short&&e._findOption(n.short),i=n.long&&e._findOption(n.long);!r&&!i?t.push(n):n.long&&!i?t.push(e.createOption(n.long,n.description)):n.short&&!r&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let e=n.options.filter(e=>!e.hidden);t.push(...e)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||``}),e.registeredArguments.find(e=>e.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(e=>xe(e)).join(` `);return e._name+(e._aliases[0]?`|`+e._aliases[0]:``)+(e.options.length?` [options]`:``)+(t?` `+t:``)}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(n)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(n)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+`|`+e._aliases[0]);let n=``;for(let t=e.parent;t;t=t.parent)n=t.name()+` `+n;return n+t+` `+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue==`boolean`)&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(`, `)}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(`, `)})`;return e.description?`${e.description} ${n}`:n}return e.description}formatItemList(e,t,n){return t.length===0?[]:[n.styleTitle(e),...t,``]}groupItems(e,t,n){let r=/* @__PURE__ */ new Map;return e.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[])}),t.forEach(e=>{let t=n(e);r.has(t)||r.set(t,[]),r.get(t).push(e)}),r}formatHelp(e,t){let n=t.padWidth(e,t),r=t.helpWidth??80;function i(e,r){return t.formatItem(e,n,r,t)}let a=[`${t.styleTitle(`Usage:`)} ${t.styleUsage(t.commandUsage(e))}`,``],o=t.commandDescription(e);o.length>0&&(a=a.concat([t.boxWrap(t.styleCommandDescription(o),r),``]));let s=t.visibleArguments(e).map(e=>i(t.styleArgumentTerm(t.argumentTerm(e)),t.styleArgumentDescription(t.argumentDescription(e))));if(a=a.concat(this.formatItemList(`Arguments:`,s,t)),this.groupItems(e.options,t.visibleOptions(e),e=>e.helpGroupHeading??`Options:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),t.showGlobalOptions){let n=t.visibleGlobalOptions(e).map(e=>i(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));a=a.concat(this.formatItemList(`Global Options:`,n,t))}return this.groupItems(e.commands,t.visibleCommands(e),e=>e.helpGroup()||`Commands:`).forEach((e,n)=>{let r=e.map(e=>i(t.styleSubcommandTerm(t.subcommandTerm(e)),t.styleSubcommandDescription(t.subcommandDescription(e))));a=a.concat(this.formatItemList(n,r,t))}),a.join(`
|
|
3
|
+
`)}displayWidth(e){return h(e).length}styleTitle(e){return e}styleUsage(e){return e.split(` `).map(e=>e===`[options]`?this.styleOptionText(e):e===`[command]`?this.styleSubcommandText(e):e[0]===`[`||e[0]===`<`?this.styleArgumentText(e):this.styleCommandText(e)).join(` `)}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(` `).map(e=>e===`[options]`?this.styleOptionText(e):e[0]===`[`||e[0]===`<`?this.styleArgumentText(e):this.styleSubcommandText(e)).join(` `)}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,n,r){let i=` `.repeat(2);if(!n)return i+e;let a=e.padEnd(t+e.length-r.displayWidth(e)),o=(this.helpWidth??80)-t-2-2,s;return s=o<this.minWidthToWrap||r.preformatted(n)?n:r.boxWrap(n,o).replace(/\n/g,`
|
|
4
4
|
`+` `.repeat(t+2)),i+a+` `.repeat(2)+s.replace(/\n/g,`\n${i}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let n=e.split(/\r\n|\n/),r=/[\s]*[^\s]+/g,i=[];return n.forEach(e=>{let n=e.match(r);if(n===null){i.push(``);return}let a=[n.shift()],o=this.displayWidth(a[0]);n.forEach(e=>{let n=this.displayWidth(e);if(o+n<=t){a.push(e),o+=n;return}i.push(a.join(``));let r=e.trimStart();a=[r],o=this.displayWidth(r)}),i.push(a.join(``))}),i.join(`
|
|
5
|
-
`)}},
|
|
5
|
+
`)}},Ce=class{constructor(e,t){this.flags=e,this.description=t||``,this.required=e.includes(`<`),this.optional=e.includes(`[`),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=Ee(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith(`--no-`)),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e==`string`&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_collectValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:(t.push(e),t)}choices(e){return this.argChoices=e.slice(),this.parseArg=(e,t)=>{if(!this.argChoices.includes(e))throw new ye(`Allowed choices are ${this.argChoices.join(`, `)}.`);return this.variadic?this._collectValue(e,t):e},this}name(){return this.long?this.long.replace(/^--/,``):this.short.replace(/^-/,``)}attributeName(){return this.negate?Te(this.name().replace(/^no-/,``)):Te(this.name())}helpGroup(e){return this.helpGroupHeading=e,this}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},we=class{constructor(e){this.positiveOptions=/* @__PURE__ */ new Map,this.negativeOptions=/* @__PURE__ */ new Map,this.dualOptions=/* @__PURE__ */ new Set,e.forEach(e=>{e.negate?this.negativeOptions.set(e.attributeName(),e):this.positiveOptions.set(e.attributeName(),e)}),this.negativeOptions.forEach((e,t)=>{this.positiveOptions.has(t)&&this.dualOptions.add(t)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let r=this.negativeOptions.get(n).presetArg,i=r!==void 0&&r;return t.negate===(i===e)}};function Te(e){return e.split(`-`).reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function Ee(e){let t,n,r=/^-[^-]$/,i=/^--[^-]/,a=e.split(/[ |,]+/).concat(`guard`);if(r.test(a[0])&&(t=a.shift()),i.test(a[0])&&(n=a.shift()),!t&&r.test(a[0])&&(t=a.shift()),!t&&i.test(a[0])&&(t=n,n=a.shift()),a[0].startsWith(`-`)){let t=a[0],n=`option creation failed due to '${t}' in option flags '${e}'`;throw/^-[^-][^-]/.test(t)?Error(`${n}
|
|
6
6
|
- a short flag is a single dash and a single character
|
|
7
7
|
- either use a single dash and a single character (for a short flag)
|
|
8
8
|
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`):r.test(t)?Error(`${n}
|
|
9
9
|
- too many short flags`):i.test(t)?Error(`${n}
|
|
10
10
|
- too many long flags`):Error(`${n}
|
|
11
|
-
- unrecognised flag format`)}if(t===void 0&&n===void 0)throw Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:t,longFlag:n}}function
|
|
12
|
-
- specify the name in Command constructor or using .name()`);return t||={},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new
|
|
13
|
-
Expecting one of '${n.join(`', '`)}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return this._exitCallback=e||(e=>{if(e.code!==`commander.executeSubCommandAsync`)throw e}),this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new
|
|
14
|
-
- already used by option '${t.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){let t=e=>[e.name()].concat(e.aliases()),n=t(e).find(e=>this._findCommand(e));if(n){let r=t(this._findCommand(n)).join(`|`),i=t(e).join(`|`);throw Error(`cannot add command '${i}' as already have command '${r}'`)}this._initCommandGroup(e),this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,`default`);let r=(t,r,i)=>{t==null&&e.presetArg!==void 0&&(t=e.presetArg);let a=this.getOptionValue(n);t!==null&&e.parseArg?t=this._callParseArg(e,t,a,r):t!==null&&e.variadic&&(t=e._collectValue(t,a)),t??=e.negate?!1:e.isBoolean()||e.optional?!0:``,this.setOptionValueWithSource(n,t,i)};return this.on(`option:`+t,t=>{let n=`error: option '${e.flags}' argument '${t}' is invalid.`;r(t,n,`cli`)}),e.envVar&&this.on(`optionEnv:`+t,t=>{let n=`error: option '${e.flags}' value '${t}' from env '${e.envVar}' is invalid.`;r(t,n,`env`)}),this}_optionEx(e,t,n,r,i){if(typeof t==`object`&&t instanceof
|
|
15
|
-
- either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(e,t,n){if(
|
|
11
|
+
- unrecognised flag format`)}if(t===void 0&&n===void 0)throw Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:t,longFlag:n}}function De(e,t){if(Math.abs(e.length-t.length)>3)return Math.max(e.length,t.length);let n=[];for(let t=0;t<=e.length;t++)n[t]=[t];for(let e=0;e<=t.length;e++)n[0][e]=e;for(let r=1;r<=t.length;r++)for(let i=1;i<=e.length;i++){let a;a=e[i-1]===t[r-1]?0:1,n[i][r]=Math.min(n[i-1][r]+1,n[i][r-1]+1,n[i-1][r-1]+a),i>1&&r>1&&e[i-1]===t[r-2]&&e[i-2]===t[r-1]&&(n[i][r]=Math.min(n[i][r],n[i-2][r-2]+1))}return n[e.length][t.length]}function Oe(e,t){if(!t||t.length===0)return``;t=Array.from(new Set(t));let n=e.startsWith(`--`);n&&(e=e.slice(2),t=t.map(e=>e.slice(2)));let r=[],i=3;return t.forEach(t=>{if(t.length<=1)return;let n=De(e,t),a=Math.max(e.length,t.length);(a-n)/a>.4&&(n<i?(i=n,r=[t]):n===i&&r.push(t))}),r.sort((e,t)=>e.localeCompare(t)),n&&(r=r.map(e=>`--${e}`)),r.length>1?`\n(Did you mean one of ${r.join(`, `)}?)`:r.length===1?`\n(Did you mean ${r[0]}?)`:``}var ke=class e extends i{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||``,this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description=``,this._summary=``,this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:e=>f.stdout.write(e),writeErr:e=>f.stderr.write(e),outputError:(e,t)=>t(e),getOutHelpWidth:()=>f.stdout.isTTY?f.stdout.columns:void 0,getErrHelpWidth:()=>f.stderr.isTTY?f.stderr.columns:void 0,getOutHasColors:()=>je()??(f.stdout.isTTY&&f.stdout.hasColors?.()),getErrHasColors:()=>je()??(f.stderr.isTTY&&f.stderr.hasColors?.()),stripColor:e=>h(e)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let r=t,i=n;typeof r==`object`&&r&&(i=r,r=null),i||={};let[,a,o]=e.match(/([^ ]+) *(.*)/),s=this.createCommand(a);return r&&(s.description(r),s._executableHandler=!0),i.isDefault&&(this._defaultCommandName=s._name),s._hidden=!!(i.noHelp||i.hidden),s._executableFile=i.executableFile||null,o&&s.arguments(o),this._registerCommand(s),s.parent=this,s.copyInheritedSettings(this),r?this:s}createCommand(t){return new e(t)}createHelp(){return Object.assign(new Se,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...e},this)}showHelpAfterError(e=!0){return typeof e!=`string`&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw Error(`Command passed to .addCommand() must have a name
|
|
12
|
+
- specify the name in Command constructor or using .name()`);return t||={},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new be(e,t)}argument(e,t,n,r){let i=this.createArgument(e,t);return typeof n==`function`?i.default(r).argParser(n):i.default(n),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(e=>{this.argument(e)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t?.variadic)throw Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e==`boolean`)return this._addImplicitHelpCommand=e,e&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;let[,n,r]=(e??`help [command]`).match(/([^ ]+) *(.*)/),i=t??`display help for command`,a=this.createCommand(n);return a.helpOption(!1),r&&a.arguments(r),i&&a.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=a,(e||t)&&this._initCommandGroup(a),this}addHelpCommand(e,t){return typeof e==`object`?(this._addImplicitHelpCommand=!0,this._helpCommand=e,this._initCommandGroup(e),this):(this.helpCommand(e,t),this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand(`help`))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let n=[`preSubcommand`,`preAction`,`postAction`];if(!n.includes(e))throw Error(`Unexpected value for event passed to hook : '${e}'.
|
|
13
|
+
Expecting one of '${n.join(`', '`)}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return this._exitCallback=e||(e=>{if(e.code!==`commander.executeSubCommandAsync`)throw e}),this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new ve(e,t,n)),f.exit(e)}action(e){let t=t=>{let n=this.registeredArguments.length,r=t.slice(0,n);return r[n]=this._storeOptionsAsProperties?this:this.opts(),r.push(this),e.apply(this,r)};return this._actionHandler=t,this}createOption(e,t){return new Ce(e,t)}_callParseArg(e,t,n,r){try{return e.parseArg(t,n)}catch(e){if(e.code===`commander.invalidArgument`){let t=`${r} ${e.message}`;this.error(t,{exitCode:e.exitCode,code:e.code})}throw e}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let n=e.long&&this._findOption(e.long)?e.long:e.short;throw Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
|
|
14
|
+
- already used by option '${t.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){let t=e=>[e.name()].concat(e.aliases()),n=t(e).find(e=>this._findCommand(e));if(n){let r=t(this._findCommand(n)).join(`|`),i=t(e).join(`|`);throw Error(`cannot add command '${i}' as already have command '${r}'`)}this._initCommandGroup(e),this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,`default`);let r=(t,r,i)=>{t==null&&e.presetArg!==void 0&&(t=e.presetArg);let a=this.getOptionValue(n);t!==null&&e.parseArg?t=this._callParseArg(e,t,a,r):t!==null&&e.variadic&&(t=e._collectValue(t,a)),t??=e.negate?!1:e.isBoolean()||e.optional?!0:``,this.setOptionValueWithSource(n,t,i)};return this.on(`option:`+t,t=>{let n=`error: option '${e.flags}' argument '${t}' is invalid.`;r(t,n,`cli`)}),e.envVar&&this.on(`optionEnv:`+t,t=>{let n=`error: option '${e.flags}' value '${t}' from env '${e.envVar}' is invalid.`;r(t,n,`env`)}),this}_optionEx(e,t,n,r,i){if(typeof t==`object`&&t instanceof Ce)throw Error(`To add an Option object use addOption() instead of option() or requiredOption()`);let a=this.createOption(t,n);if(a.makeOptionMandatory(!!e.mandatory),typeof r==`function`)a.default(i).argParser(r);else if(r instanceof RegExp){let e=r;r=(t,n)=>{let r=e.exec(t);return r?r[0]:n},a.default(i).argParser(r)}else a.default(r);return this.addOption(a)}option(e,t,n,r){return this._optionEx({},e,t,n,r)}requiredOption(e,t,n,r){return this._optionEx({mandatory:!0},e,t,n,r)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw Error(`call .storeOptionsAsProperties() before adding options`);if(Object.keys(this._optionValues).length)throw Error(`call .storeOptionsAsProperties() before setting option values`);return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(t=n.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw Error(`first parameter to parse must be array or undefined`);if(t||={},e===void 0&&t.from===void 0){f.versions?.electron&&(t.from=`electron`);let e=f.execArgv??[];(e.includes(`-e`)||e.includes(`--eval`)||e.includes(`-p`)||e.includes(`--print`))&&(t.from=`eval`)}e===void 0&&(e=f.argv),this.rawArgs=e.slice();let n;switch(t.from){case void 0:case`node`:this._scriptPath=e[1],n=e.slice(2);break;case`electron`:f.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case`user`:n=e.slice(0);break;case`eval`:n=e.slice(1);break;default:throw Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||`program`,n}parse(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_prepareForParse(){this._savedState===null?(this.options.filter(e=>e.negate&&e.defaultValue===void 0&&this.getOptionValue(e.attributeName())===void 0).forEach(e=>{let t=e.long.replace(/^--no-/,`--`);this._findOption(t)||this.setOptionValueWithSource(e.attributeName(),!0,`default`)}),this.saveStateBeforeParse()):this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw Error(`Can not call parse again when storeOptionsAsProperties is true.
|
|
15
|
+
- either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(e,t,n){if(l.existsSync(e))return;let r=`'${e}' does not exist
|
|
16
16
|
- if '${n}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
17
17
|
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
18
|
-
- ${t?`searched for local subcommand relative to directory '${t}'`:`no directory for search for local subcommand, use .executableDir() to supply a custom directory`}`;throw Error(r)}_executeSubCommand(e,t){t=t.slice();let n=[`.js`,`.ts`,`.tsx`,`.mjs`,`.cjs`];function r(e,t){let r=
|
|
19
|
-
`),this.outputHelp({error:!0}));let n=t||{},r=n.exitCode||1,i=n.code||`commander.error`;this._exit(r,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in
|
|
20
|
-
Expecting one of '${n.join(`', '`)}'`);let r=`${e}Help`;return this.on(r,e=>{let n;n=typeof t==`function`?t({error:e.error,command:e.command}):t,n&&e.write(`${n}\n`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(e=>t.is(e))&&(this.outputHelp(),this._exit(0,`commander.helpDisplayed`,`(outputHelp)`))}};function
|
|
21
|
-
`),u=!1;for(let e=0;e<l.length;e++){let t=l[e];if(r+=t,u)u=!1;else if(u=t>=`\ud800`&&t<=`\udbff`,u)continue;if(t===`\x1B`||t===``){
|
|
22
|
-
`){a&&(r+=
|
|
23
|
-
`&&(i&&
|
|
24
|
-
`)}var
|
|
18
|
+
- ${t?`searched for local subcommand relative to directory '${t}'`:`no directory for search for local subcommand, use .executableDir() to supply a custom directory`}`;throw Error(r)}_executeSubCommand(e,t){t=t.slice();let n=[`.js`,`.ts`,`.tsx`,`.mjs`,`.cjs`];function r(e,t){let r=c.resolve(e,t);if(l.existsSync(r))return r;if(n.includes(c.extname(t)))return;let i=n.find(e=>l.existsSync(`${r}${e}`));if(i)return`${r}${i}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=e._executableFile||`${this._name}-${e._name}`,o=this._executableDir||``;if(this._scriptPath){let e;try{e=l.realpathSync(this._scriptPath)}catch{e=this._scriptPath}o=c.resolve(c.dirname(e),o)}if(o){let t=r(o,i);if(!t&&!e._executableFile&&this._scriptPath){let n=c.basename(this._scriptPath,c.extname(this._scriptPath));n!==this._name&&(t=r(o,`${n}-${e._name}`))}i=t||i}let s=n.includes(c.extname(i)),u;f.platform===`win32`?(this._checkForMissingExecutable(i,o,e._name),t.unshift(i),t=Ae(f.execArgv).concat(t),u=a.spawn(f.execPath,t,{stdio:`inherit`})):s?(t.unshift(i),t=Ae(f.execArgv).concat(t),u=a.spawn(f.argv[0],t,{stdio:`inherit`})):u=a.spawn(i,t,{stdio:`inherit`}),u.killed||[`SIGUSR1`,`SIGUSR2`,`SIGTERM`,`SIGINT`,`SIGHUP`].forEach(e=>{f.on(e,()=>{u.killed===!1&&u.exitCode===null&&u.kill(e)})});let d=this._exitCallback;u.on(`close`,e=>{e??=1,d?d(new ve(e,`commander.executeSubCommandAsync`,`(close)`)):f.exit(e)}),u.on(`error`,t=>{if(t.code===`ENOENT`)this._checkForMissingExecutable(i,o,e._name);else if(t.code===`EACCES`)throw Error(`'${i}' not executable`);if(!d)f.exit(1);else{let e=new ve(1,`commander.executeSubCommandAsync`,`(error)`);e.nestedError=t,d(e)}}),this.runningCommand=u}_dispatchSubcommand(e,t,n){let r=this._findCommand(e);r||this.help({error:!0}),r._prepareForParse();let i;return i=this._chainOrCallSubCommandHook(i,r,`preSubcommand`),i=this._chainOrCall(i,()=>{if(r._executableHandler)this._executeSubCommand(r,t.concat(n));else return r._parseCommand(t,n)}),i}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??`--help`])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic||this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(e,t,n)=>{let r=t;if(t!==null&&e.parseArg){let i=`error: command-argument value '${t}' is invalid for argument '${e.name()}'.`;r=this._callParseArg(e,t,n,i)}return r};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,r)=>{let i=n.defaultValue;n.variadic?r<this.args.length?(i=this.args.slice(r),n.parseArg&&(i=i.reduce((t,r)=>e(n,r,t),n.defaultValue))):i===void 0&&(i=[]):r<this.args.length&&(i=this.args[r],n.parseArg&&(i=e(n,i,n.defaultValue))),t[r]=i}),this.processedArgs=t}_chainOrCall(e,t){return e?.then&&typeof e.then==`function`?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e,r=[];return this._getCommandAndAncestors().reverse().filter(e=>e._lifeCycleHooks[t]!==void 0).forEach(e=>{e._lifeCycleHooks[t].forEach(t=>{r.push({hookedCommand:e,callback:t})})}),t===`postAction`&&r.reverse(),r.forEach(e=>{n=this._chainOrCall(n,()=>e.callback(e.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let r=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(e=>{r=this._chainOrCall(r,()=>e(this,t))}),r}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){r(),this._processArguments();let n;return n=this._chainOrCallHooks(n,`preAction`),n=this._chainOrCall(n,()=>this._actionHandler(this.processedArgs)),this.parent&&(n=this._chainOrCall(n,()=>{this.parent.emit(i,e,t)})),n=this._chainOrCallHooks(n,`postAction`),n}if(this.parent?.listenerCount(i))r(),this._processArguments(),this.parent.emit(i,e,t);else if(e.length){if(this._findCommand(`*`))return this._dispatchSubcommand(`*`,e,t);this.listenerCount(`command:*`)?this.emit(`command:*`,e,t):this.commands.length?this.unknownCommand():(r(),this._processArguments())}else this.commands.length?(r(),this.help({error:!0})):(r(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(e=>{let t=e.attributeName();return this.getOptionValue(t)!==void 0&&this.getOptionValueSource(t)!=="default"});e.filter(e=>e.conflictsWith.length>0).forEach(t=>{let n=e.find(e=>t.conflictsWith.includes(e.attributeName()));n&&this._conflictingOption(t,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],r=t;function i(e){return e.length>1&&e[0]===`-`}let a=e=>/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(e)?!this._getCommandAndAncestors().some(e=>e.options.map(e=>e.short).some(e=>/^-\d$/.test(e))):!1,o=null,s=null,c=0;for(;c<e.length||s;){let l=s??e[c++];if(s=null,l===`--`){r===n&&r.push(l),r.push(...e.slice(c));break}if(o&&(!i(l)||a(l)))this.emit(`option:${o.name()}`,l);else{if(o=null,i(l)){let t=this._findOption(l);if(t){if(t.required){let n=e[c++];n===void 0&&this.optionMissingArgument(t),this.emit(`option:${t.name()}`,n)}else if(t.optional){let n=null;c<e.length&&(!i(e[c])||a(e[c]))&&(n=e[c++]),this.emit(`option:${t.name()}`,n)}else this.emit(`option:${t.name()}`);o=t.variadic?t:null;continue}}if(l.length>2&&l[0]===`-`&&l[1]!==`-`){let e=this._findOption(`-${l[1]}`);if(e){e.required||e.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${e.name()}`,l.slice(2)):(this.emit(`option:${e.name()}`),s=`-${l.slice(2)}`);continue}}if(/^--[^=]+=/.test(l)){let e=l.indexOf(`=`),t=this._findOption(l.slice(0,e));if(t&&(t.required||t.optional)){this.emit(`option:${t.name()}`,l.slice(e+1));continue}}if(r===t&&i(l)&&!(this.commands.length===0&&a(l))&&(r=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(l)){t.push(l),n.push(...e.slice(c));break}if(this._getHelpCommand()&&l===this._getHelpCommand().name()){t.push(l,...e.slice(c));break}if(this._defaultCommandName){n.push(l,...e.slice(c));break}}if(this._passThroughOptions){r.push(l,...e.slice(c));break}r.push(l)}}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let t=this.options[n].attributeName();e[t]=t===this._versionOptionName?this._version:this[t]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}\n`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==`string`?this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
19
|
+
`),this.outputHelp({error:!0}));let n=t||{},r=n.exitCode||1,i=n.code||`commander.error`;this._exit(r,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in f.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||[`default`,`config`,`env`].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,f.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new we(this.options),t=e=>this.getOptionValue(e)!==void 0&&![`default`,`implied`].includes(this.getOptionValueSource(e));this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(e=>{Object.keys(e.implied).filter(e=>!t(e)).forEach(t=>{this.setOptionValueWithSource(t,e.implied[t],`implied`)})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:`commander.missingArgument`})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:`commander.optionMissingArgument`})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:`commander.missingMandatoryOptionValue`})}_conflictingOption(e,t){let n=e=>{let t=e.attributeName(),n=this.getOptionValue(t),r=this.options.find(e=>e.negate&&t===e.attributeName()),i=this.options.find(e=>!e.negate&&t===e.attributeName());return r&&(r.presetArg===void 0&&n===!1||r.presetArg!==void 0&&n===r.presetArg)?r:i||e},r=e=>{let t=n(e),r=t.attributeName();return this.getOptionValueSource(r)===`env`?`environment variable '${t.envVar}'`:`option '${t.flags}'`},i=`error: ${r(e)} cannot be used with ${r(t)}`;this.error(i,{code:`commander.conflictingOption`})}unknownOption(e){if(this._allowUnknownOption)return;let t=``;if(e.startsWith(`--`)&&this._showSuggestionAfterError){let n=[],r=this;do{let e=r.createHelp().visibleOptions(r).filter(e=>e.long).map(e=>e.long);n=n.concat(e),r=r.parent}while(r&&!r._enablePositionalOptions);t=Oe(e,n)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:`commander.unknownOption`})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?``:`s`,r=e.length,i=`error: too many arguments${this.parent?` for '${this.name()}'`:``}. Expected ${t} argument${n} but got ${r}: ${e.join(`, `)}.`;this.error(i,{code:`commander.excessArguments`})}unknownCommand(){let e=this.args[0],t=``;if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(e=>{n.push(e.name()),e.alias()&&n.push(e.alias())}),t=Oe(e,n)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:`commander.unknownCommand`})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t||=`-V, --version`,n||=`output the version number`;let r=this.createOption(t,n);return this._versionOptionName=r.attributeName(),this._registerOption(r),this.on(`option:`+r.name(),()=>{this._outputConfiguration.writeOut(`${e}\n`),this._exit(0,`commander.version`,e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw Error(`Command alias can't be the same as its name`);let n=this.parent?._findCommand(e);if(n){let t=[n.name()].concat(n.aliases()).join(`|`);throw Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${t}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(e=>this.alias(e)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let e=this.registeredArguments.map(e=>xe(e));return[].concat(this.options.length||this._helpOption!==null?`[options]`:[],this.commands.length?`[command]`:[],this.registeredArguments.length?e:[]).join(` `)}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}helpGroup(e){return e===void 0?this._helpGroupHeading??``:(this._helpGroupHeading=e,this)}commandsGroup(e){return e===void 0?this._defaultCommandGroup??``:(this._defaultCommandGroup=e,this)}optionsGroup(e){return e===void 0?this._defaultOptionGroup??``:(this._defaultOptionGroup=e,this)}_initOptionGroup(e){this._defaultOptionGroup&&!e.helpGroupHeading&&e.helpGroup(this._defaultOptionGroup)}_initCommandGroup(e){this._defaultCommandGroup&&!e.helpGroup()&&e.helpGroup(this._defaultCommandGroup)}nameFromFilename(e){return this._name=c.basename(e,c.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp(),n=this._getOutputContext(e);t.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let r=t.formatHelp(this,t);return n.hasColors?r:this._outputConfiguration.stripColor(r)}_getOutputContext(e){e||={};let t=!!e.error,n,r,i;return t?(n=e=>this._outputConfiguration.writeErr(e),r=this._outputConfiguration.getErrHasColors(),i=this._outputConfiguration.getErrHelpWidth()):(n=e=>this._outputConfiguration.writeOut(e),r=this._outputConfiguration.getOutHasColors(),i=this._outputConfiguration.getOutHelpWidth()),{error:t,write:e=>(r||(e=this._outputConfiguration.stripColor(e)),n(e)),hasColors:r,helpWidth:i}}outputHelp(e){let t;typeof e==`function`&&(t=e,e=void 0);let n=this._getOutputContext(e),r={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach(e=>e.emit(`beforeAllHelp`,r)),this.emit(`beforeHelp`,r);let i=this.helpInformation({error:n.error});if(t&&(i=t(i),typeof i!=`string`&&!Buffer.isBuffer(i)))throw Error(`outputHelp callback must return a string or a Buffer`);n.write(i),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit(`afterHelp`,r),this._getCommandAndAncestors().forEach(e=>e.emit(`afterAllHelp`,r))}helpOption(e,t){return typeof e==`boolean`?(e?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(e??`-h, --help`,t??`display help for command`),(e||t)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this._initOptionGroup(e),this}help(e){this.outputHelp(e);let t=Number(f.exitCode??0);t===0&&e&&typeof e!=`function`&&e.error&&(t=1),this._exit(t,`commander.help`,`(outputHelp)`)}addHelpText(e,t){let n=[`beforeAll`,`before`,`after`,`afterAll`];if(!n.includes(e))throw Error(`Unexpected value for position to addHelpText.
|
|
20
|
+
Expecting one of '${n.join(`', '`)}'`);let r=`${e}Help`;return this.on(r,e=>{let n;n=typeof t==`function`?t({error:e.error,command:e.command}):t,n&&e.write(`${n}\n`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(e=>t.is(e))&&(this.outputHelp(),this._exit(0,`commander.helpDisplayed`,`(outputHelp)`))}};function Ae(e){return e.map(e=>{if(!e.startsWith(`--inspect`))return e;let t,n=`127.0.0.1`,r=`9229`,i;return(i=e.match(/^(--inspect(-brk)?)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],r=i[4]):(t=i[1],/^\d+$/.test(i[3])?r=i[3]:n=i[3]):t=i[1],t&&r!==`0`?`${t}=${n}:${parseInt(r)+1}`:e})}function je(){if(f.env.NO_COLOR||f.env.FORCE_COLOR===`0`||f.env.FORCE_COLOR===`false`)return!1;if(f.env.FORCE_COLOR||f.env.CLICOLOR_FORCE!==void 0)return!0}new ke;const Me=`0.7.0`,Ne=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return t=>{let n=0;for(e.lastIndex=0;e.test(t);)n+=1;return t.length-n}})(),Pe=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,Fe=e=>e===8987||e===9001||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141,Ie=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,Le=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Re=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/uy,ze=/\t{1,1000}/y,Be=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/uy,Ve=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,He=/\p{M}+/gu,Ue={limit:1/0,ellipsis:``},We=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??``,a=t?.ellipsisWidth??(i?We(i,Ue,n).width:0),o=n.controlWidth??0,s=n.tabWidth??8,c=n.emojiWidth??2,l=n.regularWidth??1,u=n.wideWidth??2,d=[[Ve,l],[Ie,0],[Le,o],[ze,s],[Be,c],[Re,u]],f=0,p=0,m=e.length,h=0,g=!1,_=m,v=Math.max(0,r-a),y=0,b=0,x=0,S=0;outer:for(;;){if(b>y||p>=m&&p>f){let t=e.slice(y,b)||e.slice(f,p);h=0;for(let e of t.replaceAll(He,``)){let t=e.codePointAt(0)||0;if(S=Pe(t)?2:Fe(t)?u:l,x+S>v&&(_=Math.min(_,Math.max(y,f)+h)),x+S>r){g=!0;break outer}h+=e.length,x+=S}y=b=0}if(p>=m)break outer;for(let t=0,n=d.length;t<n;t++){let[n,i]=d[t];if(n.lastIndex=p,n.test(e)){if(h=n===Re?Ne(e.slice(p,n.lastIndex)):n===Be?1:n.lastIndex-p,S=h*i,x+S>v&&(_=Math.min(_,p+Math.floor((v-x)/i))),x+S>r){g=!0;break outer}x+=S,y=f,b=p,p=f=n.lastIndex;continue outer}}p+=1}return{width:g?v:x,index:g?_:m,truncated:g,ellipsed:g&&r>=a}},Ge={limit:1/0,ellipsis:``,ellipsisWidth:0},w=(e,t={})=>We(e,Ge,t).width,Ke=`]8;;`,qe=RegExp(`(?:\\[(?<code>\\d+)m|\\${Ke}(?<uri>.*))`,`y`),Je=e=>{if(e>=30&&e<=37||e>=90&&e<=97)return 39;if(e>=40&&e<=47||e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0},Ye=e=>`[${e}m`,Xe=e=>`${Ke}${e}`,Ze=(e,t,n)=>{let r=t[Symbol.iterator](),i=!1,a=!1,o=e.at(-1),s=o===void 0?0:w(o),c=r.next(),l=r.next(),u=0;for(;!c.done;){let o=c.value,d=w(o);s+d<=n?e[e.length-1]+=o:(e.push(o),s=0),(o===`\x1B`||o===``)&&(i=!0,a=t.startsWith(Ke,u+1)),i?a?o===`\x07`&&(i=!1,a=!1):o===`m`&&(i=!1):(s+=d,s===n&&!l.done&&(e.push(``),s=0)),c=l,l=r.next(),u+=o.length}o=e.at(-1),!s&&o!==void 0&&o.length&&e.length>1&&(e[e.length-2]+=e.pop())},Qe=e=>{let t=e.split(` `),n=t.length;for(;n&&!w(t[n-1]);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},$e=(e,t,n={})=>{if(n.trim!==!1&&e.trim()===``)return``;let r=``,i,a,o=e.split(` `),s=[``],c=0;for(let e=0;e<o.length;e++){let r=o[e];if(n.trim!==!1){let e=s.at(-1)??``,t=e.trimStart();e.length!==t.length&&(s[s.length-1]=t,c=w(t))}e!==0&&(c>=t&&(n.wordWrap===!1||n.trim===!1)&&(s.push(``),c=0),(c||n.trim===!1)&&(s[s.length-1]+=` `,c++));let i=w(r);if(n.hard&&i>t){let e=t-c,n=1+Math.floor((i-e-1)/t);Math.floor((i-1)/t)<n&&s.push(``),Ze(s,r,t),c=w(s.at(-1)??``)}else{if(c+i>t&&c&&i){if(n.wordWrap===!1&&c<t){Ze(s,r,t),c=w(s.at(-1)??``);continue}s.push(``),c=0}c+i>t&&n.wordWrap===!1?(Ze(s,r,t),c=w(s.at(-1)??``)):(s[s.length-1]+=r,c+=i)}}n.trim!==!1&&(s=s.map(e=>Qe(e)));let l=s.join(`
|
|
21
|
+
`),u=!1;for(let e=0;e<l.length;e++){let t=l[e];if(r+=t,u)u=!1;else if(u=t>=`\ud800`&&t<=`\udbff`,u)continue;if(t===`\x1B`||t===``){qe.lastIndex=e+1;let t=qe.exec(l)?.groups;if(t?.code!==void 0){let e=Number.parseFloat(t.code);i=e===39?void 0:e}else t?.uri!==void 0&&(a=t.uri.length===0?void 0:t.uri)}if(l[e+1]===`
|
|
22
|
+
`){a&&(r+=Xe(``));let e=i?Je(i):void 0;i&&e&&(r+=Ye(e))}else t===`
|
|
23
|
+
`&&(i&&Je(i)&&(r+=Ye(i)),a&&(r+=Xe(a)))}return r},et=/\r?\n/;function T(e,t,n){return String(e).normalize().split(et).map(e=>$e(e,t,n)).join(`
|
|
24
|
+
`)}var E=(/* @__PURE__ */ he(((e,t)=>{let n={to(e,t){return t?`[${t+1};${e+1}H`:`[${e+1}G`},move(e,t){let n=``;return e<0?n+=`[${-e}D`:e>0&&(n+=`[${e}C`),t<0?n+=`[${-t}A`:t>0&&(n+=`[${t}B`),n},up:(e=1)=>`[${e}A`,down:(e=1)=>`[${e}B`,forward:(e=1)=>`[${e}C`,backward:(e=1)=>`[${e}D`,nextLine:(e=1)=>`\x1B[E`.repeat(e),prevLine:(e=1)=>`\x1B[F`.repeat(e),left:`\x1B[G`,hide:`\x1B[?25l`,show:`\x1B[?25h`,save:`\x1B7`,restore:`\x1B8`};t.exports={cursor:n,scroll:{up:(e=1)=>`\x1B[S`.repeat(e),down:(e=1)=>`\x1B[T`.repeat(e)},erase:{screen:`\x1B[2J`,up:(e=1)=>`\x1B[1J`.repeat(e),down:(e=1)=>`\x1B[J`.repeat(e),line:`\x1B[2K`,lineEnd:`\x1B[K`,lineStart:`\x1B[1K`,lines(e){let t=``;for(let r=0;r<e;r++)t+=this.line+(r<e-1?n.up():``);return e&&(t+=n.left),t}},beep:`\x07`}})))();function D(e,t,n){if(!n.some(e=>!e.disabled))return e;let r=e+t,i=Math.max(n.length-1,0),a=r<0?i:r>i?0:r;return n[a]?.disabled?D(a,t<0?-1:1,n):a}const O={actions:/* @__PURE__ */ new Set([`up`,`down`,`left`,`right`,`space`,`enter`,`cancel`]),aliases:/* @__PURE__ */ new Map([[`k`,`up`],[`j`,`down`],[`h`,`left`],[`l`,`right`],[``,`cancel`],[`escape`,`cancel`]]),messages:{cancel:`Canceled`,error:`Something went wrong`},withGuide:!0,accessible:void 0,date:{monthNames:[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],messages:{required:`Please enter a valid date`,invalidMonth:`There are only 12 months in a year`,invalidDay:(e,t)=>`There are only ${e} days in ${t}`,afterMin:e=>`Date must be on or after ${e.toISOString().slice(0,10)}`,beforeMax:e=>`Date must be on or before ${e.toISOString().slice(0,10)}`}}};function tt(e){if(e!==void 0)return e;if(O.accessible!==void 0)return O.accessible;let t=process.env.ACCESSIBLE;return t!==void 0&&t!==``&&t!==`0`&&t!==`false`}function nt(e,t){if(typeof e==`string`)return O.aliases.get(e)===t;for(let n of e)if(n!==void 0&&nt(n,t))return!0;return!1}function rt(e,t){if(e===t)return;let n=e.split(`
|
|
25
25
|
`),r=t.split(`
|
|
26
|
-
`),i=Math.max(n.length,r.length),a=[];for(let e=0;e<i;e++)n[e]!==r[e]&&a.push(e);return{lines:a,numLinesBefore:n.length,numLinesAfter:r.length,numLines:i}}const
|
|
26
|
+
`),i=Math.max(n.length,r.length),a=[];for(let e=0;e<i;e++)n[e]!==r[e]&&a.push(e);return{lines:a,numLinesBefore:n.length,numLinesAfter:r.length,numLines:i}}const it=globalThis.process.platform.startsWith(`win`),at=Symbol(`clack:cancel`);function ot(e){return e===at}function st(e,t){let n=e;n.isTTY&&n.setRawMode(t)}function ct({input:e=p,output:t=m,overwrite:n=!0,hideCursor:r=!0}={}){let i=v.createInterface({input:e,output:t,prompt:``,tabSize:1});v.emitKeypressEvents(e,i),e instanceof y&&e.isTTY&&e.setRawMode(!0);let a=(i,{name:o,sequence:s})=>{if(nt([String(i),o,s],`cancel`)){r&&t.write(E.cursor.show),process.exit(0);return}if(!n)return;let c=o===`return`?0:-1,l=o===`return`?-1:0;v.moveCursor(t,c,l,()=>{v.clearLine(t,1,()=>{e.once(`keypress`,a)})})};return r&&t.write(E.cursor.hide),e.once(`keypress`,a),()=>{e.off(`keypress`,a),r&&t.write(E.cursor.show),e instanceof y&&e.isTTY&&!it&&e.setRawMode(!1),i.terminal=!1,i.close()}}const lt=e=>`columns`in e&&typeof e.columns==`number`?e.columns:80,ut=e=>`rows`in e&&typeof e.rows==`number`?e.rows:20;function k(e,t,n,r=n,i=n,a){return T(t,lt(e??m)-n.length,{hard:!0,trim:!1}).split(`
|
|
27
27
|
`).map((e,t,o)=>{let s=a?a(e,t):e;return t===0?`${r}${s}`:t===o.length-1?`${i}${s}`:`${n}${s}`}).join(`
|
|
28
|
-
`)}function
|
|
29
|
-
`),
|
|
30
|
-
`).length-1;this.output.write(
|
|
31
|
-
`);this.output.write(t[a]),this._prevFrame=e,this.output.write(
|
|
28
|
+
`)}function dt(e,t){if(`~standard`in e){let n=e[`~standard`].validate(t);return n instanceof Promise?n.then(e=>e.issues?.at(0)?.message):n.issues?.at(0)?.message}return e(t)}var ft=class{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame=``;_subscribers=/* @__PURE__ */ new Map;_cursor=0;state=`initial`;error=``;value;userInput=``;get accessible(){return tt(this.opts.accessible)}constructor(e,t=!0){let{input:n=p,output:r=m,render:i,signal:a,...o}=e;this.opts=o,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=i.bind(this),this._track=t,this._abortSignal=a,this.input=n,this.output=r}unsubscribe(){this._subscribers.clear()}setSubscriber(e,t){let n=this._subscribers.get(e)??[];n.push(t),this._subscribers.set(e,n)}on(e,t){this.setSubscriber(e,{cb:t})}once(e,t){this.setSubscriber(e,{cb:t,once:!0})}emit(e,...t){let n=this._subscribers.get(e)??[],r=[];for(let e of n)e.cb(...t),e.once&&r.push(()=>n.splice(n.indexOf(e),1));for(let e of r)e()}prompt(){return new Promise(e=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state=`cancel`,this.close(),e(at);this._abortSignal.addEventListener(`abort`,()=>{this.state=`cancel`,this.close()},{once:!0})}this.rl=_.createInterface({input:this.input,tabSize:2,prompt:``,escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on(`keypress`,this.onKeypress),st(this.input,!0),this.output.on(`resize`,this.render),this.render(),this.once(`submit`,()=>{this.output.write(E.cursor.show),this.output.off(`resize`,this.render),st(this.input,!1),e(this.value)}),this.once(`cancel`,()=>{this.output.write(E.cursor.show),this.output.off(`resize`,this.render),st(this.input,!1),e(at)})})}_isActionKey(e,t){return e===` `}_shouldSubmit(e,t){return!0}_setValue(e){this.value=e,this.emit(`value`,this.value)}_setUserInput(e,t){this.userInput=e??``,this.emit(`userInput`,this.userInput),t&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:`u`}),this._setUserInput(``)}async onKeypress(e,t){if(this.state!==`validating`){if(this._track&&t.name!==`return`&&(t.name&&this._isActionKey(e,t)&&this.rl?.write(null,{ctrl:!0,name:`h`}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state===`error`&&(this.state=`active`),t?.name&&(!this._track&&O.aliases.has(t.name)&&this.emit(`cursor`,O.aliases.get(t.name)),O.actions.has(t.name)&&this.emit(`cursor`,t.name)),e&&(e.toLowerCase()===`y`||e.toLowerCase()===`n`)&&this.emit(`confirm`,e.toLowerCase()===`y`),this.emit(`key`,e,t),t?.name===`return`&&this._shouldSubmit(e,t)){if(this.opts.validate){let e=dt(this.opts.validate,this.value),t;e instanceof Promise?(this.state=`validating`,this.render(),t=await e):t=e,t&&(this.error=t instanceof Error?t.message:t,this.state=`error`,this.rl?.write(this.userInput))}this.state!==`error`&&(this.state=`submit`)}nt([e,t?.name,t?.sequence],`cancel`)&&(this.state=`cancel`),(this.state===`submit`||this.state===`cancel`)&&this.emit(`finalize`),this.render(),(this.state===`submit`||this.state===`cancel`)&&this.close()}}close(){this.input.unpipe(),this.input.removeListener(`keypress`,this.onKeypress),this.output.write(`
|
|
29
|
+
`),st(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=T(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
|
|
30
|
+
`).length-1;this.output.write(E.cursor.move(-999,e*-1))}render(){let e=T(this._render(this)??``,process.stdout.columns,{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state===`initial`)this.output.write(E.cursor.hide);else{let t=rt(this._prevFrame,e),n=ut(this.output);if(this.restoreCursor(),t){let r=Math.max(0,t.numLinesAfter-n),i=Math.max(0,t.numLinesBefore-n),a=t.lines.find(e=>e>=r);if(a===void 0){this._prevFrame=e;return}if(t.lines.length===1){this.output.write(E.cursor.move(0,a-i)),this.output.write(E.erase.lines(1));let t=e.split(`
|
|
31
|
+
`);this.output.write(t[a]),this._prevFrame=e,this.output.write(E.cursor.move(0,t.length-a-1));return}if(t.lines.length>1){if(r<i)a=r;else{let e=a-i;e>0&&this.output.write(E.cursor.move(0,e))}this.output.write(E.erase.down());let t=e.split(`
|
|
32
32
|
`).slice(a);this.output.write(t.join(`
|
|
33
|
-
`)),this._prevFrame=e;return}}this.output.write(
|
|
34
|
-
`);_.push(a),v+=a.length}if(v>u){let t=0,n=0,r=v,i=e-y,a=u,o=()=>
|
|
33
|
+
`)),this._prevFrame=e;return}}this.output.write(E.erase.down())}this.output.write(e),this.state===`initial`&&(this.state=`active`),this._prevFrame=e}}},pt=class extends ft{get cursor(){return+!this.value}get _value(){return this.cursor===0}constructor(e){super(e,!1),this.value=!!e.initialValue,this.on(`userInput`,()=>{this.value=this._value}),this.on(`confirm`,e=>{this.output.write(E.cursor.move(0,-1)),this.value=e,this.state=`submit`,this.close()}),this.on(`cursor`,()=>{this.value=!this.value})}},mt=class extends ft{options;cursor=0;get _value(){return this.options[this.cursor]?.value}get _enabledOptions(){return this.options.filter(e=>e.disabled!==!0)}toggleAll(){let e=this._enabledOptions,t=this.value!==void 0&&this.value.length===e.length;this.value=t?[]:e.map(e=>e.value)}toggleInvert(){let e=this.value;if(!e)return;let t=this._enabledOptions.filter(t=>!e.includes(t.value));this.value=t.map(e=>e.value)}toggleValue(){this.value===void 0&&(this.value=[]);let e=this.value.includes(this._value);this.value=e?this.value.filter(e=>e!==this._value):[...this.value,this._value]}constructor(e){super(e,!1),this.options=e.options,this.value=[...e.initialValues??[]];let t=Math.max(this.options.findIndex(({value:t})=>t===e.cursorAt),0);this.cursor=this.options[t]?.disabled?D(t,1,this.options):t,this.on(`key`,(e,t)=>{t.name===`a`&&this.toggleAll(),t.name===`i`&&this.toggleInvert()}),this.on(`cursor`,e=>{switch(e){case`left`:case`up`:this.cursor=D(this.cursor,-1,this.options);break;case`down`:case`right`:this.cursor=D(this.cursor,1,this.options);break;case`space`:this.toggleValue()}})}};let ht=class extends ft{_mask=`•`;get cursor(){return this._cursor}get masked(){return this.userInput.replaceAll(/./g,this._mask)}get userInputWithCursor(){if(this.state===`submit`||this.state===`cancel`)return this.masked;let e=this.userInput;if(this.cursor>=e.length)return`${this.masked}${g([`inverse`,`hidden`],`_`)}`;let t=this.masked,n=t.slice(0,this.cursor),r=t.slice(this.cursor,this.cursor+1),i=t.slice(this.cursor+1);return`${n}${g(`inverse`,r)}${i}`}clear(){this._clearUserInput()}constructor({mask:e,...t}){super(t),this._mask=e??`•`,this.on(`userInput`,e=>{this._setValue(e)}),this.on(`finalize`,()=>{this.value===void 0&&(this.value=``)})}},gt=class extends ft{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){let e=this._selectedValue;this.value=e===void 0?void 0:e.value}constructor(e){super(e,!1),this.options=e.options;let t=this.options.findIndex(({value:t})=>t===e.initialValue),n=t===-1?0:t;this.cursor=this.options[n]?.disabled?D(n,1,this.options):n,this.changeValue(),this.on(`cursor`,e=>{switch(e){case`left`:case`up`:this.cursor=D(this.cursor,-1,this.options);break;case`down`:case`right`:this.cursor=D(this.cursor,1,this.options)}this.changeValue()})}};var _t=class extends ft{get userInputWithCursor(){if(this.state===`submit`)return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${this.userInput}\u2588`;let t=e.slice(0,this.cursor),n=e.slice(this.cursor,this.cursor+1),r=e.slice(this.cursor+1);return`${t}${g(`inverse`,n)}${r}`}get cursor(){return this._cursor}constructor(e){super({...e,initialUserInput:e.initialUserInput??e.initialValue}),this.on(`userInput`,e=>{this._setValue(e)}),this.on(`finalize`,()=>{this.value||=e.defaultValue,this.value===void 0&&(this.value=``)})}};function vt(){return f.platform===`win32`?!!f.env.CI||!!f.env.WT_SESSION||!!f.env.TERMINUS_SUBLIME||f.env.ConEmuTask===`{cmd::Cmder}`||f.env.TERM_PROGRAM===`Terminus-Sublime`||f.env.TERM_PROGRAM===`vscode`||f.env.TERM===`xterm-256color`||f.env.TERM===`alacritty`||f.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:f.env.TERM!==`linux`}const yt=vt(),bt=()=>process.env.CI===`true`,A=(e,t)=>yt?e:t,xt=A(`◆`,`*`),St=A(`■`,`x`),Ct=A(`▲`,`x`),wt=A(`◇`,`o`),j=A(`│`,`|`),M=A(`└`,`—`),Tt=A(`●`,`>`),Et=A(`○`,` `),Dt=A(`◻`,`[•]`),Ot=A(`◼`,`[+]`),kt=A(`◻`,`[ ]`),At=A(`▪`,`•`),jt=A(`─`,`-`),Mt=A(`╮`,`+`),Nt=A(`├`,`+`),Pt=A(`╯`,`+`),Ft=A(`╰`,`+`),It=e=>{switch(e){case`initial`:case`active`:return g(`cyan`,xt);case`cancel`:return g(`red`,St);case`error`:return g(`yellow`,Ct);case`submit`:return g(`green`,wt);case`validating`:return g(`dim`,xt)}},Lt=e=>{switch(e){case`initial`:case`active`:return g(`cyan`,j);case`cancel`:return g(`red`,j);case`error`:return g(`yellow`,j);case`submit`:return g(`green`,j)}};function Rt(e,t){let n=[`${t?`${g(`cyan`,j)} `:``}${e.join(` • `)}`];return t&&n.push(g(`cyan`,M)),n}const zt=(e,t,n,r,i,a=!1)=>{let o=t,s=0;if(a)for(let t=r-1;t>=n;t--){let n=e[t];if(n&&(o-=n.length),s++,o<=i)break}else for(let t=n;t<r;t++){let n=e[t];if(n&&(o-=n.length),s++,o<=i)break}return{lineCount:o,removals:s}},Bt=({cursor:e,options:t,style:n,output:r=process.stdout,maxItems:i=1/0,columnPadding:a=0,rowPadding:o=4})=>{let s=lt(r)-a,c=ut(r),l=g(`dim`,`...`),u=Math.max(c-o,0),d=Math.max(Math.min(i,u),5),f=0;e>=d-3&&(f=Math.max(Math.min(e-d+3,t.length-d),0));let p=d<t.length&&f>0,m=d<t.length&&f+d<t.length,h=Math.min(f+d,t.length),_=[],v=0;p&&v++,m&&v++;let y=f+ +!!p,b=h-+!!m;for(let r=y;r<b;r++){let i=t[r],a=T(i?n(i,r===e):``,s,{hard:!0,trim:!1}).split(`
|
|
34
|
+
`);_.push(a),v+=a.length}if(v>u){let t=0,n=0,r=v,i=e-y,a=u,o=()=>zt(_,r,0,i,a),s=()=>zt(_,r,i+1,_.length,a,!0);p?({lineCount:r,removals:t}=o(),r>a&&(m||--a,{lineCount:r,removals:n}=s())):(m||--a,{lineCount:r,removals:n}=s(),r>a&&(--a,{lineCount:r,removals:t}=o())),t>0&&(p=!0,_.splice(0,t)),n>0&&(m=!0,_.splice(_.length-n,n))}let x=[];p&&x.push(l);for(let e of _)for(let t of e)x.push(t);return m&&x.push(l),x},Vt=e=>{let t=e.active??`Yes`,n=e.inactive??`No`;return new pt({active:t,inactive:n,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let r=e.withGuide??O.withGuide,i=`${It(this.state)} `,a=r?`${g(`gray`,j)} `:``,o=k(e.output,e.message,a,i),s=`${r?`${g(`gray`,j)}
|
|
35
35
|
`:``}${o}
|
|
36
|
-
`,c=this.value?t:n;switch(this.state){case`submit`:return`${s}${r?`${
|
|
37
|
-
${
|
|
38
|
-
${
|
|
39
|
-
`:` ${
|
|
36
|
+
`,c=this.value?t:n;switch(this.state){case`submit`:return`${s}${r?`${g(`gray`,j)} `:``}${g(`dim`,c)}`;case`cancel`:return`${s}${r?`${g(`gray`,j)} `:``}${g([`strikethrough`,`dim`],c)}${r?`
|
|
37
|
+
${g(`gray`,j)}`:``}`;default:{let i=r?`${g(`cyan`,j)} `:``,a=r?g(`cyan`,M):``;return`${s}${i}${this.value?`${g(`green`,Tt)} ${t}`:`${g(`dim`,Et)} ${g(`dim`,t)}`}${e.vertical?r?`
|
|
38
|
+
${g(`cyan`,j)} `:`
|
|
39
|
+
`:` ${g(`dim`,`/`)} `}${this.value?`${g(`dim`,Et)} ${g(`dim`,n)}`:`${g(`green`,Tt)} ${n}`}
|
|
40
40
|
${a}
|
|
41
|
-
`}}}}).prompt()},
|
|
41
|
+
`}}}}).prompt()},Ht=[`${g(`dim`,`↑/↓`)} to navigate`,`${g(`dim`,`Space:`)} select`,`${g(`dim`,`Enter:`)} confirm`],Ut=(e,t)=>e.split(`
|
|
42
42
|
`).map(e=>t(e)).join(`
|
|
43
|
-
`),
|
|
44
|
-
${
|
|
43
|
+
`),N=e=>{let t=(e,t)=>{let n=e.label??String(e.value);return t===`disabled`?`${g(`gray`,kt)} ${Ut(n,e=>g([`strikethrough`,`gray`],e))}${e.hint?` ${g(`dim`,`(${e.hint??`disabled`})`)}`:``}`:t===`active`?`${g(`cyan`,Dt)} ${n}${e.hint?` ${g(`dim`,`(${e.hint})`)}`:``}`:t===`selected`?`${g(`green`,Ot)} ${Ut(n,e=>g(`dim`,e))}${e.hint?` ${g(`dim`,`(${e.hint})`)}`:``}`:t===`cancelled`?`${Ut(n,e=>g([`strikethrough`,`dim`],e))}`:t===`active-selected`?`${g(`green`,Ot)} ${n}${e.hint?` ${g(`dim`,`(${e.hint})`)}`:``}`:t===`submitted`?`${Ut(n,e=>g(`dim`,e))}`:`${g(`dim`,kt)} ${Ut(n,e=>g(`dim`,e))}`},n=e.required??!0,r=e.showInstructions??!0;return new mt({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValues:e.initialValues,required:n,cursorAt:e.cursorAt,validate(e){if(n&&(e===void 0||e.length===0))return`Please select at least one option.
|
|
44
|
+
${g(`reset`,g(`dim`,`Press ${g([`gray`,`bgWhite`,`inverse`],` space `)} to select, ${g(`gray`,g(`bgWhite`,g(`inverse`,` enter `)))} to submit`))}`},render(){let n=e.withGuide??O.withGuide,i=k(e.output,e.message,n?`${Lt(this.state)} `:``,`${It(this.state)} `),a=`${n?`${g(`gray`,j)}
|
|
45
45
|
`:``}${i}
|
|
46
|
-
`,o=this.value??[],s=(e,n)=>{if(e.disabled)return t(e,`disabled`);let r=o.includes(e.value);return n&&r?t(e,`active-selected`):r?t(e,`selected`):t(e,n?`active`:`inactive`)};switch(this.state){case`submit`:{let r=this.options.filter(({value:e})=>o.includes(e)).map(e=>t(e,`submitted`)).join(
|
|
47
|
-
${
|
|
48
|
-
`).map((e,t)=>t===0?`${n?`${
|
|
46
|
+
`,o=this.value??[],s=(e,n)=>{if(e.disabled)return t(e,`disabled`);let r=o.includes(e.value);return n&&r?t(e,`active-selected`):r?t(e,`selected`):t(e,n?`active`:`inactive`)};switch(this.state){case`submit`:{let r=this.options.filter(({value:e})=>o.includes(e)).map(e=>t(e,`submitted`)).join(g(`dim`,`, `))||g(`dim`,`none`);return`${a}${k(e.output,r,n?`${g(`gray`,j)} `:``)}`}case`cancel`:{let r=this.options.filter(({value:e})=>o.includes(e)).map(e=>t(e,`cancelled`)).join(g(`dim`,`, `));return r.trim()===``?`${a}${g(`gray`,j)}`:`${a}${k(e.output,r,n?`${g(`gray`,j)} `:``)}${n?`
|
|
47
|
+
${g(`gray`,j)}`:``}`}case`error`:{let t=n?`${g(`yellow`,j)} `:``,r=this.error.split(`
|
|
48
|
+
`).map((e,t)=>t===0?`${n?`${g(`yellow`,M)} `:``}${g(`yellow`,e)}`:` ${e}`).join(`
|
|
49
49
|
`),i=a.split(`
|
|
50
50
|
`).length,o=r.split(`
|
|
51
|
-
`).length+1;return`${a}${t}${
|
|
51
|
+
`).length+1;return`${a}${t}${Bt({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:t.length,rowPadding:i+o,style:s}).join(`
|
|
52
52
|
${t}`)}
|
|
53
53
|
${r}
|
|
54
|
-
`}default:{let t=n?`${
|
|
55
|
-
`).length,o=r?
|
|
56
|
-
`),l=o.length+1;return`${a}${t}${
|
|
54
|
+
`}default:{let t=n?`${g(`cyan`,j)} `:``,i=a.split(`
|
|
55
|
+
`).length,o=r?Rt(Ht,n):n?[g(`cyan`,M)]:[],c=o.join(`
|
|
56
|
+
`),l=o.length+1;return`${a}${t}${Bt({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:t.length,rowPadding:i+l,style:s}).join(`
|
|
57
57
|
${t}`)}
|
|
58
58
|
${c}
|
|
59
|
-
`}}}}).prompt()},
|
|
59
|
+
`}}}}).prompt()},Wt=(e=``,t)=>{let n=t?.output??process.stdout,r=t?.withGuide??O.withGuide?`${g(`gray`,M)} `:``;n.write(`${r}${g(`red`,e)}
|
|
60
60
|
|
|
61
|
-
`)},
|
|
62
|
-
${
|
|
61
|
+
`)},Gt=(e=``,t)=>{let n=t?.output??process.stdout,r=t?.withGuide??O.withGuide?`${g(`gray`,j)}
|
|
62
|
+
${g(`gray`,M)} `:``;n.write(`${r}${e}
|
|
63
63
|
|
|
64
|
-
`)},
|
|
65
|
-
`),a=i.reduce((e,t)=>Math.max(
|
|
66
|
-
`).map(a),``],s=
|
|
67
|
-
`),u=i?`${
|
|
68
|
-
`:``,
|
|
64
|
+
`)},Kt=e=>e,qt=(e,t,n)=>{let r={hard:!0,trim:!1},i=T(e,t,r).split(`
|
|
65
|
+
`),a=i.reduce((e,t)=>Math.max(w(t),e),0);return T(e,t-(i.map(n).reduce((e,t)=>Math.max(w(t),e),0)-a),r)},P=(e=``,t=``,n)=>{let r=n?.output??f.stdout,i=n?.withGuide??O.withGuide,a=n?.format??Kt,o=[``,...qt(e,lt(r)-6,a).split(`
|
|
66
|
+
`).map(a),``],s=w(t),c=Math.max(o.reduce((e,t)=>{let n=w(t);return n>e?n:e},0),s)+2,l=o.map(e=>`${g(`gray`,j)} ${e}${` `.repeat(c-w(e))}${g(`gray`,j)}`).join(`
|
|
67
|
+
`),u=i?`${g(`gray`,j)}
|
|
68
|
+
`:``,d=i?Nt:Ft;r.write(`${u}${g(`green`,wt)} ${g(`reset`,t)} ${g(`gray`,jt.repeat(Math.max(c-s-1,1))+Mt)}
|
|
69
69
|
${l}
|
|
70
|
-
${
|
|
71
|
-
`)},
|
|
72
|
-
`:``}${
|
|
73
|
-
`,r=this.userInputWithCursor,i=this.masked;switch(this.state){case`error`:{let r=t?`${
|
|
70
|
+
${g(`gray`,d+jt.repeat(c+2)+Pt)}
|
|
71
|
+
`)},Jt=e=>new ht({validate:e.validate,mask:e.mask??At,signal:e.signal,input:e.input,output:e.output,render(){let t=e.withGuide??O.withGuide,n=`${t?`${g(`gray`,j)}
|
|
72
|
+
`:``}${It(this.state)} ${e.message}
|
|
73
|
+
`,r=this.userInputWithCursor,i=this.masked;switch(this.state){case`error`:{let r=t?`${g(`yellow`,j)} `:``,a=t?`${g(`yellow`,M)} `:``,o=i??``;return e.clearOnError&&this.clear(),`${n.trim()}
|
|
74
74
|
${r}${o}
|
|
75
|
-
${a}${
|
|
76
|
-
`}case`submit`:return`${n}${t?`${
|
|
77
|
-
${
|
|
78
|
-
${t?
|
|
79
|
-
`}}}).prompt(),
|
|
80
|
-
`);let e=
|
|
81
|
-
`);e.length>1&&n.write(
|
|
82
|
-
`);let r=0,i=0;
|
|
75
|
+
${a}${g(`yellow`,this.error)}
|
|
76
|
+
`}case`submit`:return`${n}${t?`${g(`gray`,j)} `:``}${i?g(`dim`,i):``}`;case`cancel`:return`${n}${t?`${g(`gray`,j)} `:``}${i?g([`strikethrough`,`dim`],i):``}${i&&t?`
|
|
77
|
+
${g(`gray`,j)}`:``}`;default:return`${n}${t?`${g(`cyan`,j)} `:``}${r}
|
|
78
|
+
${t?g(`cyan`,M):``}
|
|
79
|
+
`}}}).prompt(),Yt=e=>g(`magenta`,e),Xt=({indicator:e=`dots`,onCancel:t,output:n=process.stdout,cancelMessage:r,errorMessage:i,frames:a=yt?[`◒`,`◐`,`◓`,`◑`]:[`•`,`o`,`O`,`0`],delay:o=yt?80:120,signal:s,...c}={})=>{let l=bt(),u,d,f=!1,p=!1,m=``,h,_=performance.now(),v=lt(n),y=c?.styleFrame??Yt,b=e=>{let n=e>1?i??O.messages.error:r??O.messages.cancel;p=e===1,f&&(oe(n,e),p&&typeof t==`function`&&t())},x=()=>b(2),S=()=>b(1),ee=()=>{process.on(`uncaughtExceptionMonitor`,x),process.on(`unhandledRejection`,x),process.on(`SIGINT`,S),process.on(`SIGTERM`,S),process.on(`exit`,b),s&&s.addEventListener(`abort`,S)},C=()=>{process.removeListener(`uncaughtExceptionMonitor`,x),process.removeListener(`unhandledRejection`,x),process.removeListener(`SIGINT`,S),process.removeListener(`SIGTERM`,S),process.removeListener(`exit`,b),s&&s.removeEventListener(`abort`,S)},te=()=>{if(h===void 0)return;l&&n.write(`
|
|
80
|
+
`);let e=T(h,v,{hard:!0,trim:!1}).split(`
|
|
81
|
+
`);e.length>1&&n.write(E.cursor.up(e.length-1)),n.write(E.cursor.to(0)),n.write(E.erase.down())},ne=e=>e.replace(/\.+$/,``),re=e=>{let t=(performance.now()-e)/1e3,n=Math.floor(t/60),r=Math.floor(t%60);return n>0?`[${n}m ${r}s]`:`[${r}s]`},ie=c.withGuide??O.withGuide,ae=(t=``)=>{f=!0,u=ct({output:n}),m=ne(t),_=performance.now(),ie&&n.write(`${g(`gray`,j)}
|
|
82
|
+
`);let r=0,i=0;ee(),d=setInterval(()=>{if(l&&m===h)return;te(),h=m;let t=y(a[r]),o;if(l)o=`${t} ${m}...`;else if(e===`timer`)o=`${t} ${m} ${re(_)}`;else{let e=`.`.repeat(Math.floor(i)).slice(0,3);o=`${t} ${m}${e}`}let s=T(o,v,{hard:!0,trim:!1});n.write(s),r=r+1<a.length?r+1:0,i=i<4?i+.125:0},o)},oe=(t=``,r=0,i=!1)=>{if(!f)return;f=!1,clearInterval(d),te();let a=r===0?g(`green`,wt):r===1?g(`red`,St):g(`red`,Ct);m=t??m,i||(e===`timer`?n.write(`${a} ${m} ${re(_)}
|
|
83
83
|
`):n.write(`${a} ${m}
|
|
84
|
-
`)),
|
|
84
|
+
`)),C(),u()};return{start:ae,stop:(e=``)=>oe(e,0),message:(e=``)=>{m=ne(e??m)},cancel:(e=``)=>oe(e,1),error:(e=``)=>oe(e,2),clear:()=>oe(``,0,!0),get isCancelled(){return p}}},Zt=[`${g(`dim`,`↑/↓`)} to navigate`,`${g(`dim`,`Enter:`)} confirm`],Qt=(e,t)=>e.includes(`
|
|
85
85
|
`)?e.split(`
|
|
86
86
|
`).map(e=>t(e)).join(`
|
|
87
|
-
`):t(e),
|
|
87
|
+
`):t(e),F=e=>{let t=(e,t)=>{if(e===void 0)return``;let n=e.label??String(e.value);switch(t){case`disabled`:return`${g(`gray`,Et)} ${Qt(n,e=>g(`gray`,e))}${e.hint?` ${g(`dim`,`(${e.hint??`disabled`})`)}`:``}`;case`selected`:return`${Qt(n,e=>g(`dim`,e))}`;case`active`:return`${g(`green`,Tt)} ${n}${e.hint?` ${g(`dim`,`(${e.hint})`)}`:``}`;case`cancelled`:return`${Qt(n,e=>g([`strikethrough`,`dim`],e))}`;default:return`${g(`dim`,Et)} ${Qt(n,e=>g(`dim`,e))}`}},n=e.showInstructions??!0;return new gt({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let r=e.withGuide??O.withGuide,i=`${It(this.state)} `,a=`${Lt(this.state)} `,o=k(e.output,e.message,a,i),s=`${r?`${g(`gray`,j)}
|
|
88
88
|
`:``}${o}
|
|
89
|
-
`;switch(this.state){case`submit`:{let n=r?`${
|
|
90
|
-
${
|
|
91
|
-
`).length,o=n?
|
|
92
|
-
`),l=o.length+1;return`${s}${i}${
|
|
89
|
+
`;switch(this.state){case`submit`:{let n=r?`${g(`gray`,j)} `:``;return`${s}${k(e.output,t(this.options[this.cursor],`selected`),n)}`}case`cancel`:{let n=r?`${g(`gray`,j)} `:``;return`${s}${k(e.output,t(this.options[this.cursor],`cancelled`),n)}${r?`
|
|
90
|
+
${g(`gray`,j)}`:``}`}default:{let i=r?`${g(`cyan`,j)} `:``,a=s.split(`
|
|
91
|
+
`).length,o=n?Rt(Zt,r):r?[g(`cyan`,M)]:[],c=o.join(`
|
|
92
|
+
`),l=o.length+1;return`${s}${i}${Bt({output:e.output,cursor:this.cursor,options:this.options,maxItems:e.maxItems,columnPadding:i.length,rowPadding:a+l,style:(e,n)=>t(e,e.disabled?`disabled`:n?`active`:`inactive`)}).join(`
|
|
93
93
|
${i}`)}
|
|
94
94
|
${c}
|
|
95
|
-
`}}}}).prompt()};`${
|
|
96
|
-
`:``}${
|
|
97
|
-
`,r=e.placeholder&&e.placeholder.length>0?
|
|
98
|
-
${r} ${
|
|
99
|
-
`}case`error`:{let e=this.error?` ${
|
|
95
|
+
`}}}}).prompt()};`${g(`gray`,j)}`;const $t=e=>new _t({validate:e.validate,placeholder:e.placeholder,defaultValue:e.defaultValue,initialValue:e.initialValue,output:e.output,signal:e.signal,input:e.input,render(){let t=e?.withGuide??O.withGuide,n=`${`${t?`${g(`gray`,j)}
|
|
96
|
+
`:``}${It(this.state)} `}${e.message}
|
|
97
|
+
`,r=e.placeholder&&e.placeholder.length>0?g(`inverse`,e.placeholder[0])+g(`dim`,e.placeholder.slice(1)):g([`inverse`,`hidden`],`_`),i=this.userInput?this.userInputWithCursor:r,a=this.value??``;switch(this.state){case`validating`:{let e=t?`${g(`cyan`,j)} `:``,r=t?g(`cyan`,M):``;return`${n}${e}${g(`dim`,i)}
|
|
98
|
+
${r} ${g(`dim`,`Validating...`)}
|
|
99
|
+
`}case`error`:{let e=this.error?` ${g(`yellow`,this.error)}`:``,r=t?`${g(`yellow`,j)} `:``,a=t?g(`yellow`,M):``;return`${n.trim()}
|
|
100
100
|
${r}${i}
|
|
101
101
|
${a}${e}
|
|
102
|
-
`}case`submit`:{let e=a?`${t?` `:``}${
|
|
103
|
-
${r}`:``}`}default:return`${n}${t?`${
|
|
104
|
-
${t?
|
|
105
|
-
`}}}).prompt();var
|
|
106
|
-
`)}function
|
|
107
|
-
`);return await
|
|
108
|
-
`)}\n`}function
|
|
109
|
-
`}function
|
|
102
|
+
`}case`submit`:{let e=a?`${t?` `:``}${g(`dim`,a)}`:``;return`${n}${t?g(`gray`,j):``}${e}`}case`cancel`:{let e=a?` ${g([`strikethrough`,`dim`],a)}`:``,r=t?g(`gray`,j):``;return`${n}${r}${e}${a.trim()?`
|
|
103
|
+
${r}`:``}`}default:return`${n}${t?`${g(`cyan`,j)} `:``}${i}
|
|
104
|
+
${t?g(`cyan`,M):``}
|
|
105
|
+
`}}}).prompt();var en=/* @__PURE__ */ he(((e,t)=>{let n=process||{},r=n.argv||[],i=n.env||{},a=!(i.NO_COLOR||r.includes(`--no-color`))&&(!!i.FORCE_COLOR||r.includes(`--color`)||n.platform===`win32`||(n.stdout||{}).isTTY&&i.TERM!==`dumb`||!!i.CI),o=(e,t,n=e)=>r=>{let i=``+r,a=i.indexOf(t,e.length);return~a?e+s(i,t,n,a)+t:e+i+t},s=(e,t,n,r)=>{let i=``,a=0;do i+=e.substring(a,r)+n,a=r+t.length,r=e.indexOf(t,a);while(~r);return i+e.substring(a)},c=(e=a)=>{let t=e?o:()=>String;return{isColorSupported:e,reset:t(`\x1B[0m`,`\x1B[0m`),bold:t(`\x1B[1m`,`\x1B[22m`,`\x1B[22m\x1B[1m`),dim:t(`\x1B[2m`,`\x1B[22m`,`\x1B[22m\x1B[2m`),italic:t(`\x1B[3m`,`\x1B[23m`),underline:t(`\x1B[4m`,`\x1B[24m`),inverse:t(`\x1B[7m`,`\x1B[27m`),hidden:t(`\x1B[8m`,`\x1B[28m`),strikethrough:t(`\x1B[9m`,`\x1B[29m`),black:t(`\x1B[30m`,`\x1B[39m`),red:t(`\x1B[31m`,`\x1B[39m`),green:t(`\x1B[32m`,`\x1B[39m`),yellow:t(`\x1B[33m`,`\x1B[39m`),blue:t(`\x1B[34m`,`\x1B[39m`),magenta:t(`\x1B[35m`,`\x1B[39m`),cyan:t(`\x1B[36m`,`\x1B[39m`),white:t(`\x1B[37m`,`\x1B[39m`),gray:t(`\x1B[90m`,`\x1B[39m`),bgBlack:t(`\x1B[40m`,`\x1B[49m`),bgRed:t(`\x1B[41m`,`\x1B[49m`),bgGreen:t(`\x1B[42m`,`\x1B[49m`),bgYellow:t(`\x1B[43m`,`\x1B[49m`),bgBlue:t(`\x1B[44m`,`\x1B[49m`),bgMagenta:t(`\x1B[45m`,`\x1B[49m`),bgCyan:t(`\x1B[46m`,`\x1B[49m`),bgWhite:t(`\x1B[47m`,`\x1B[49m`),blackBright:t(`\x1B[90m`,`\x1B[39m`),redBright:t(`\x1B[91m`,`\x1B[39m`),greenBright:t(`\x1B[92m`,`\x1B[39m`),yellowBright:t(`\x1B[93m`,`\x1B[39m`),blueBright:t(`\x1B[94m`,`\x1B[39m`),magentaBright:t(`\x1B[95m`,`\x1B[39m`),cyanBright:t(`\x1B[96m`,`\x1B[39m`),whiteBright:t(`\x1B[97m`,`\x1B[39m`),bgBlackBright:t(`\x1B[100m`,`\x1B[49m`),bgRedBright:t(`\x1B[101m`,`\x1B[49m`),bgGreenBright:t(`\x1B[102m`,`\x1B[49m`),bgYellowBright:t(`\x1B[103m`,`\x1B[49m`),bgBlueBright:t(`\x1B[104m`,`\x1B[49m`),bgMagentaBright:t(`\x1B[105m`,`\x1B[49m`),bgCyanBright:t(`\x1B[106m`,`\x1B[49m`),bgWhiteBright:t(`\x1B[107m`,`\x1B[49m`)}};t.exports=c(),t.exports.createColors=c}));const tn=/* @__PURE__ */ new Set([`.git`,`.next`,`.turbo`,`build`,`coverage`,`dist`,`node_modules`]);async function nn(e){let t=[];return await dn(e,async n=>{if(!ln(c.basename(n)))return;let r=await C(n,`utf8`);t.push({path:n,relativePath:c.relative(e,n)||c.basename(n),variables:rn(r)})}),t.sort((t,n)=>un(t,e)-un(n,e)||t.relativePath.localeCompare(n.relativePath))}function rn(e){let t={};for(let n of e.split(/\r?\n/)){let e=/^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(n.trim());if(!e)continue;let[,r,i]=e;r!==void 0&&i!==void 0&&(t[r]=cn(i))}return t}function an(e){return Object.keys(e.variables).sort((e,t)=>e===`DATABASE_URL`?-1:t===`DATABASE_URL`?1:e.localeCompare(t))}function on(e,t){if(!e)return`<vazio>`;if(t===`DATABASE_URL`){let t=e.replace(/:\/\/([^:]+):[^@]+@/,`://$1:****@`);if(t!==e)return t.replace(/([?#]).*$/,`$1****`);let n=e.indexOf(`://`);return n>=0?`${e.slice(0,n+3)}****`:`****`}return`****`}function sn(e,t){return Object.values(t).filter(e=>e.length>0).sort((e,t)=>t.length-e.length).reduce((e,t)=>e.replaceAll(t,`[REDACTED]`),e)}function cn(e){return e.startsWith(`"`)&&e.endsWith(`"`)||e.startsWith(`'`)&&e.endsWith(`'`)?e.slice(1,-1):e.replace(/\s+#.*$/,``).trim()}function ln(e){if(e===`.env`)return!0;if(!e.startsWith(`.env.`))return!1;let t=e.slice(5).toLowerCase();return![`example`,`sample`,`template`].includes(t)&&!t.endsWith(`.example`)&&!t.endsWith(`.sample`)&&!t.endsWith(`.template`)}function un(e,t){let n=c.relative(t,e.path).split(c.sep).length-1,r=c.basename(e.path)===`.env`?0:1;return n*10+r}async function dn(e,t){let n=await te(e,{withFileTypes:!0});for(let r of n)r.isDirectory()&&!tn.has(r.name)?await dn(c.join(e,r.name),t):r.isFile()&&await t(c.join(e,r.name))}async function I(e,t,n){await new Promise((r,i)=>{let a=o(e,t,{cwd:n.cwd,stdio:`inherit`,shell:process.platform===`win32`});a.on(`error`,i),a.on(`exit`,n=>{n===0?r():i(/* @__PURE__ */ Error(`Comando falhou: ${e} ${t.join(` `)}`))})})}async function fn(e,t={}){let r=await(t.run??((e,t,r)=>n(e,t,{cwd:r.cwd,env:r.env})))(e.command,e.args,{cwd:e.script.packageDir,env:{...process.env,...e.envFile.variables}});return{status:r.exitCode===0?`ok`:`error`,exitCode:r.exitCode,stdout:sn(r.stdout,e.envFile.variables),stderr:sn(r.stderr,e.envFile.variables)}}const pn=[`db:migrate`,`migrate:db`,`database:migrate`,`migrate:database`,`migration:run`,`migrations:run`,`prisma:migrate`,`drizzle:migrate`,`typeorm:migration:run`,`sequelize:migrate`,`knex:migrate`,`db:up`];async function mn(e){let t=[];await xn(e,async e=>{c.basename(e)===`package.json`&&t.push(e)});let n=[],r=[];for(let i of t.sort())try{let t=JSON.parse(await C(i,`utf8`)),r=t.scripts;if(!r||typeof r!=`object`)continue;let a=c.dirname(i),o=await vn(a,e,typeof t.packageManager==`string`?t.packageManager:void 0);for(let[s,l]of Object.entries(r))typeof l==`string`&&n.push({packageJsonPath:i,relativePackageJsonPath:c.relative(e,i)||`package.json`,packageDir:a,packageName:typeof t.name==`string`?t.name:void 0,packageManager:o,name:s,command:l})}catch{r.push(`Não foi possível ler ${c.relative(e,i)||`package.json`}.`)}return{scripts:n,warnings:r}}function hn(e){let t=e.filter(e=>gn(e.name)>0).sort(bn);return{usedFallback:t.length===0,scripts:t.length>0?t:[...e].sort(bn)}}function gn(e){let t=e.toLowerCase(),n=pn.indexOf(t);if(n>=0)return 100-n;let r=/(^|:)(db|database|migration|migrations)(:|$)/.test(t),i=/(^|:)(migrate|run|up|apply)(:|$)/.test(t);return r&&i?10:0}function _n(e){return{command:e.packageManager,args:[`run`,e.name]}}async function vn(e,t,n){if(n){let e=n.split(`@`)[0];if(e!==void 0&&yn(e))return e}for(let[t,n]of[[`bun.lock`,`bun`],[`bun.lockb`,`bun`],[`pnpm-lock.yaml`,`pnpm`],[`yarn.lock`,`yarn`],[`package-lock.json`,`npm`]])if(await Sn(c.join(e,t)))return n;if(e!==t){for(let[e,n]of[[`bun.lock`,`bun`],[`bun.lockb`,`bun`],[`pnpm-lock.yaml`,`pnpm`],[`yarn.lock`,`yarn`],[`package-lock.json`,`npm`]])if(await Sn(c.join(t,e)))return n}return`npm`}function yn(e){return[`bun`,`npm`,`pnpm`,`yarn`].includes(e)}function bn(e,t){return gn(t.name)-gn(e.name)||e.relativePackageJsonPath.localeCompare(t.relativePackageJsonPath)||e.name.localeCompare(t.name)}async function xn(e,t){let n=await te(e,{withFileTypes:!0});for(let r of n)r.isDirectory()&&!tn.has(r.name)?await xn(c.join(e,r.name),t):r.isFile()&&await t(c.join(e,r.name))}async function Sn(e){try{return await b(e),!0}catch{return!1}}var L=/* @__PURE__ */ _e(en(),1);function R(e,t=`Operacao cancelada.`){return ot(e)&&(Wt(t),process.exit(0)),e}function Cn(e){e.command(`db`).description(`Operações de banco de dados`).command(`migrate`).description(`Executa a migration do projeto usando um arquivo .env`).action(async()=>{try{await wn(process.cwd())}catch(e){console.error(`${L.default.red(`ERROR`)} ${e instanceof Error?e.message:String(e)}`),process.exitCode=1}})}async function wn(e){let t=await nn(e);if(t.length===0)throw Error(`Nenhum arquivo .env encontrado no projeto. Crie um arquivo .env antes de executar a migration.`);let n=R(await F({message:`Qual arquivo de ambiente deseja usar?`,...t[0]===void 0?{}:{initialValue:t[0].relativePath},options:t.map(e=>({value:e.relativePath,label:e.relativePath,hint:`${Object.keys(e.variables).length} variável(is)${e.variables.DATABASE_URL?` · DATABASE_URL encontrada`:``}`}))}),`Operação cancelada.`),r=t.find(e=>e.relativePath===n);if(!r)throw Error(`O arquivo de ambiente selecionado não foi encontrado.`);let i=an(r);if(i.length===0)throw Error(`Nenhuma variável válida foi encontrada em ${r.relativePath}.`);r.variables.DATABASE_URL||P(`Não foi encontrada a variável DATABASE_URL neste arquivo. Selecione outra chave ou cancele a operação.`,`Atenção`);let a=R(await F({message:`Qual variável contém a conexão do banco?`,...i[0]===void 0?{}:{initialValue:i[0]},options:i.map(e=>({value:e,label:e,...e===`DATABASE_URL`?{hint:`padrão`}:{}}))}),`Operação cancelada.`),o=await mn(e);for(let e of o.warnings)P(e,`Aviso`);if(o.scripts.length===0)throw Error(`Nenhum script foi encontrado nos package.json do projeto.`);let s=hn(o.scripts),c=await Tn(s.scripts,s.usedFallback),l=_n(c),u={envFile:r,envKey:a,envValue:r.variables[a]??``,script:c,command:l.command,args:l.args};if(P(En(u),`Confirmação da migration`),!R(await Vt({message:`Deseja executar esta migration agora?`,initialValue:!1}),`Operação cancelada.`)){Gt(`Migration não executada.`);return}let d=Xt();d.start(`Executando migration...`);try{let e=await fn(u);d.stop(e.status===`ok`?L.default.green(`Migration concluída.`):L.default.red(`Migration falhou (exit code ${e.exitCode}).`)),Dn(e.stdout,e.stderr),e.status===`error`&&(process.exitCode=1)}catch(e){throw d.stop(L.default.red(`Não foi possível executar a migration.`)),e}}async function Tn(e,t){for(t&&P(`Nenhum nome conhecido de migration foi encontrado. Selecione manualmente um script disponível.`,`Atenção`);;){let t=R(await N({message:`Qual script de migration deseja executar? Selecione exatamente um.`,options:e.map((e,t)=>({value:`${t}`,label:`${e.relativePackageJsonPath} · ${e.name}`,hint:`${e.packageManager} run ${e.name} — ${e.command}`}))}),`Operação cancelada.`),n=e[Number(t[0])];if(t.length===1&&n)return n;P(`Selecione exatamente um script para evitar executar migrations em sequência.`,`Atenção`)}}function En(e){return[`Arquivo: ${e.envFile.relativePath}`,`Variável: ${e.envKey}`,`Valor: ${on(e.envValue,e.envKey)}`,`Pacote: ${e.script.relativePackageJsonPath}`,`Diretório: ${e.script.packageDir}`,`Package manager: ${e.script.packageManager}`,`Script: ${e.script.name}`,`Comando: ${[e.command,...e.args].join(` `)}`,`Variáveis injetadas: ${Object.keys(e.envFile.variables).length}`].join(`
|
|
106
|
+
`)}function Dn(e,t){e.trim()&&console.log(`\n${e.trim()}`),t.trim()&&console.error(`\n${L.default.yellow(t.trim())}`)}var On=class extends Error{constructor(e){super(`Arquivo ${e} nao encontrado. Crie-o na raiz do projeto antes de executar este comando.`),this.name=`EnvFileNotFoundError`}};async function kn(e,t){try{return await C(e,`utf8`)}catch(e){throw e.code===`ENOENT`?new On(t):e}}function An(e){return e.split(/\r?\n/).map(Mn).filter(e=>e!==void 0).filter((e,t,n)=>n.indexOf(e)===t)}function jn(e){let t=Mn(e);return t?`${t}=`:e}function Mn(e){let t=e.trim().replace(/^export\s+/,``);if(t&&!t.startsWith(`#`))return t.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*(?:=|$)/)?.[1]}async function Nn(e=process.cwd()){let t=c.join(e,`.env`),n=c.join(e,`.env.example`),r=await kn(t,`.env`),i=r.split(/\r?\n/).map(jn).join(`
|
|
107
|
+
`);return await ie(n,i,`utf8`),{path:n,keys:An(r)}}async function Pn(e=process.cwd()){let[t,n]=await Promise.all([kn(c.join(e,`.env`),`.env`),kn(c.join(e,`.env.example`),`.env.example`)]),r=An(t),i=An(n);return{envKeys:r,exampleKeys:i,missingInEnv:i.filter(e=>!r.includes(e))}}function Fn(e){let t=e.command(`env`).description(`Gera e valida o arquivo .env.example`);t.command(`example`).description(`Gera .env.example a partir do .env, sem valores`).action(async()=>{let e=await In(()=>Nn(process.cwd()));e&&console.log(`${L.default.green(`OK`)} .env.example gerado com ${e.keys.length} chave(s).`)}),t.command(`check`).description(`Verifica se o .env possui todas as chaves do .env.example`).action(async()=>{let e=await In(()=>Pn(process.cwd()));e&&(e.missingInEnv.length===0?console.log(`${L.default.green(`OK`)} .env possui todas as ${e.exampleKeys.length} chave(s) de .env.example.`):(console.error(`${L.default.red(`ERROR`)} Chaves ausentes no .env: ${e.missingInEnv.join(`, `)}`),process.exitCode=1))})}async function In(e){try{return await e()}catch(e){if(e instanceof On){console.error(`${L.default.red(`ERROR`)} ${e.message}`),process.exitCode=1;return}throw e}}function Ln(e){let t=e.toLowerCase();return t===`agents.md`||t===`claude.md`||t===`contributing.md`}async function Rn(e){try{await S(e,{recursive:!1})}catch(t){if(t.code!==`EEXIST`)throw t;if((await te(e,{withFileTypes:!0})).filter(e=>!(e.isFile()&&Ln(e.name))).length>0)throw Error(`A pasta "${c.basename(e)}" ja existe.`)}}async function zn(e,t){for(let n of t){let t=c.join(e,n.path);if(await S(c.dirname(t),{recursive:!0}),n.symlinkTarget)await ne(t,{force:!0}),await re(n.symlinkTarget,t);else{if(n.content===void 0)throw Error(`Arquivo de template sem conteudo: ${n.path}`);await ie(t,n.content,`utf8`)}}}function Bn(e){return e===`pnpm`?`pnpm@10.30.2`:`bun@1.2.20`}function Vn(e,t){return e===`pnpm`?`pnpm exec ${t}`:`bunx ${t}`}function z(e,t,n){return e===`pnpm`?`pnpm --filter ${t} ${n}`:`bun --filter ${t} ${n}`}const Hn=c.dirname(ae(import.meta.url)),Un=c.resolve(Hn,`../template-assets`),Wn=c.join(Hn,`cli/template-assets`);let Gn;function Kn(){return Gn||(Gn=u(Un)?Un:Wn,Gn)}function qn(e){return c.join(Kn(),e)}function Jn(e){return d(qn(e),`utf8`)}function Yn(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).replace(/-{2,}/g,`-`)}const Xn=`1.4.4`,Zn=[`node`,`bun`];function Qn(e){if(e.runtime===`bun`){if(e.templateId===`web`)return`O runtime bun vale para API e workers; o template web continua em Node.`;if(e.apiHosting===`cloudflare`)return`O runtime bun nao combina com a API no Cloudflare Workers, que roda no workerd (nem Node, nem Bun).`;if(e.packageManager===`pnpm`)return`O runtime bun usa o Bun como gerenciador de pacotes: troque --package-manager pnpm por bun.`}}function $n(e={}){let t=e.predev?`${e.predev} && `:``;return{dev:`${t}bun --watch src/main.ts`,start:`bun src/main.ts`,"start:dev":`${t}bun --watch src/main.ts`,"start:prod":`bun src/main.ts`,test:`bun test --pass-with-no-tests`}}function er(e){return e.replaceAll(`node --test`,`bun test --pass-with-no-tests`)}function tr(e){let{"tsc-watch":t,...n}=e;return{...n,"@types/bun":`latest`}}function nr(e){return!!(e&&Object.keys(e).length>0)}function B(e){return`${JSON.stringify(e,null,` `)}\n`}function V(e){return B({name:e.name,version:e.version??`0.1.0`,description:e.description,private:e.privatePackage??!0,...e.type?{type:e.type}:{},packageManager:e.runtime===`bun`?`bun@${Xn}`:Bn(e.packageManager),...e.sideEffects===void 0?{}:{sideEffects:e.sideEffects},engines:e.engines??(e.runtime===`bun`?{bun:`>=1.4.4`}:{node:`>=20.0.0`}),...e.keywords?.length?{keywords:e.keywords}:{},...e.bin?{bin:e.bin}:{},...e.main?{main:e.main}:{},...e.module?{module:e.module}:{},...e.types?{types:e.types}:{},...e.exports?{exports:e.exports}:{},...e.files?.length?{files:e.files}:{},...e.extraFields??{},scripts:e.scripts,...nr(e.dependencies)?{dependencies:e.dependencies}:{},...nr(e.devDependencies)?{devDependencies:e.runtime===`bun`&&e.devDependencies?tr(e.devDependencies):e.devDependencies}:{}})}function H(e){return B({...e.extends?{extends:e.extends}:{},compilerOptions:e.compilerOptions,...e.include?{include:e.include}:{},...e.exclude?{exclude:e.exclude}:{}})}function rr(e){return`${[`# dependencies (bun install)`,`node_modules`,``,`# output`,`out`,`dist`,`*.tgz`,...e?.outputEntries??[],``,`# code coverage`,`coverage`,`*.lcov`,``,`# logs`,`logs`,`*.log`,`report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json`,``,`# dotenv environment variable files`,`.env`,`.env.development.local`,`.env.test.local`,`.env.production.local`,`.env.local`,``,`# caches`,`.eslintcache`,`.cache`,`*.tsbuildinfo`,...e?.cacheEntries??[],``,`# IntelliJ based IDEs`,`.idea`,``,`# Finder (MacOS) folder config`,`.DS_Store`,...e?.extraEntries?.length?[``,...e.extraEntries]:[]].join(`
|
|
108
|
+
`)}\n`}function ir(){return`export default { extends: ['@commitlint/config-conventional'] };
|
|
109
|
+
`}function ar(){return`services:
|
|
110
110
|
pg:
|
|
111
111
|
image: postgres:16-alpine
|
|
112
112
|
ports:
|
|
@@ -140,13 +140,13 @@ ${t?h(`cyan`,N):``}
|
|
|
140
140
|
volumes:
|
|
141
141
|
pg-data:
|
|
142
142
|
dragonflydata:
|
|
143
|
-
`}function
|
|
143
|
+
`}function or(e,t,n,r=!1){let i=t?`@${n}/database/schema`:`./src/modules/database/schema`;return`// Node-only configuration for Better Auth schema generation.
|
|
144
144
|
import 'dotenv/config';
|
|
145
145
|
import { createAuth } from './src/auth';
|
|
146
146
|
${e?`import { Pool } from 'pg';
|
|
147
147
|
import { drizzle } from 'drizzle-orm/node-postgres';
|
|
148
148
|
import * as schema from '${i}';
|
|
149
|
-
const client = drizzle(new Pool({ connectionString: process.env.DATABASE_URL }), { schema });`:`import { PrismaClient } from '@prisma/client';
|
|
149
|
+
const client = drizzle(new Pool({ connectionString: process.env.DATABASE_URL }), { schema, casing: 'snake_case' });`:`import { PrismaClient } from '@prisma/client';
|
|
150
150
|
import { PrismaPg } from '@prisma/adapter-pg';
|
|
151
151
|
const client = new PrismaClient({ adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL }) });`}
|
|
152
152
|
|
|
@@ -156,7 +156,7 @@ ${r?` messagingService: {
|
|
|
156
156
|
async sendEmail() { throw new Error('Schema generation must not send email.'); },
|
|
157
157
|
},`:``}
|
|
158
158
|
});
|
|
159
|
-
`}const
|
|
159
|
+
`}const sr=`2026-10-05`,cr=`deploy/wrangler.jsonc`,lr=`postgresql://docker:docker@127.0.0.1:7000/rock`;function ur(e){return e.replace(/ {2}REDIS_(?:URL|PASSWORD): str\(\{[\s\S]*?\}\),\n/g,``).replace(/^REDIS_(?:URL|PASSWORD)=.*\n/gm,``)}function dr(e,t){return`${t?`import { Injectable, type OnModuleDestroy } from '@nestjs/common';
|
|
160
160
|
`:``}import { env } from 'cloudflare:workers';
|
|
161
161
|
${e?`import { Pool } from 'pg';
|
|
162
162
|
import { drizzle } from 'drizzle-orm/node-postgres';
|
|
@@ -168,16 +168,17 @@ ${t?`@Injectable()
|
|
|
168
168
|
// Constructed inside the Worker invocation, never at module scope.
|
|
169
169
|
private readonly connectionString = (env as { HYPERDRIVE: Hyperdrive }).HYPERDRIVE.connectionString;
|
|
170
170
|
${e?` private readonly pool = new Pool({ connectionString: this.connectionString, max: 1 });
|
|
171
|
-
readonly client = drizzle(this.pool, { schema });`:` readonly client = new PrismaClient({ adapter: new PrismaPg({ connectionString: this.connectionString, max: 1 }) });`}
|
|
171
|
+
readonly client = drizzle(this.pool, { schema, casing: 'snake_case' });`:` readonly client = new PrismaClient({ adapter: new PrismaPg({ connectionString: this.connectionString, max: 1 }) });`}
|
|
172
172
|
async connect() { return this.client; }
|
|
173
173
|
async ping(): Promise<string> {
|
|
174
174
|
${e?`await this.pool.query('SELECT 1');`:"await this.client.$queryRaw`SELECT 1`;"}
|
|
175
|
+
|
|
175
176
|
return 'up';
|
|
176
177
|
}
|
|
177
178
|
async disconnect(): Promise<void> { ${e?`await this.pool.end();`:`await this.client.$disconnect();`} }
|
|
178
179
|
${t?` async onModuleDestroy(): Promise<void> { await this.disconnect(); }
|
|
179
180
|
`:``}}
|
|
180
|
-
`}function
|
|
181
|
+
`}function fr(){return`services:
|
|
181
182
|
postgres:
|
|
182
183
|
image: postgres:17-alpine
|
|
183
184
|
environment:
|
|
@@ -193,7 +194,7 @@ ${t?` async onModuleDestroy(): Promise<void> { await this.disconnect(); }
|
|
|
193
194
|
retries: 10
|
|
194
195
|
volumes:
|
|
195
196
|
postgres_data:
|
|
196
|
-
`}function
|
|
197
|
+
`}function pr(e,t,n,r,i,a){a(`${t}package.json`,e=>{e.type=`module`,e.engines={...e.engines,node:`>=22`},e.dependencies={...e.dependencies,next:`^16.4.0`,react:`^19.2.6`,"react-dom":`^19.2.6`,"react-server-dom-webpack":`^19.2.6`,vinext:`^1.0.1`,...n?{}:{"@vinext/cloudflare":`^1.0.1`}},e.devDependencies={...e.devDependencies,"@types/react":`^19.2.0`,"@types/react-dom":`^19.2.0`,"@vitejs/plugin-react":`^6.1.2`,"@vitejs/plugin-rsc":`^0.5.36`,vite:`^8.3.4`,wrangler:`^4.149.0`,"@cloudflare/workers-types":`^5.20261005.1`,...n?{}:{"@cloudflare/vite-plugin":`^1.63.1`}},e.scripts[`dev:vinext`]=`vinext dev --port 3000`,e.scripts[`build:vinext`]=`vite build`,n?(e.scripts.start=`wrangler dev --config ${cr} --port 3000`,e.scripts.preview=`vite build && ${e.scripts.start}`,e.scripts.deploy=`vite build && wrangler deploy --config ${cr}`):(e.scripts.preview=`vite build && wrangler dev --config dist/server/wrangler.json --port 3000`,e.scripts.deploy=`vinext-cloudflare deploy --config dist/server/wrangler.json`,e.scripts[`cf:typegen`]=`wrangler types`)});let o=JSON.parse(r(`${t}tsconfig.json`));o.compilerOptions.jsx=`react-jsx`,o.include=[...o.include,`.next/dev/types/**/*.ts`],i(`${t}tsconfig.json`,B(o));let s=r(`.oxfmtrc.json`);s&&i(`.oxfmtrc.json`,B({...JSON.parse(s),ignorePatterns:[`**/next-env.d.ts`]})),i(`${t}vite.config.ts`,n?`import vinext from 'vinext';
|
|
197
198
|
import { defineConfig } from 'vite';
|
|
198
199
|
|
|
199
200
|
export default defineConfig({
|
|
@@ -211,42 +212,55 @@ export default defineConfig({
|
|
|
211
212
|
}),
|
|
212
213
|
],
|
|
213
214
|
});
|
|
214
|
-
`),i(`${t}${n?
|
|
215
|
+
`),i(`${t}${n?cr:`wrangler.jsonc`}`,B({$schema:`${n?`../`:``}node_modules/wrangler/config-schema.json`,name:`${e.projectSlug}-web`,compatibility_date:sr,...n?{assets:{directory:`../dist/client`,html_handling:`force-trailing-slash`,not_found_handling:`404-page`}}:{main:`vinext/server/fetch-handler`,compatibility_flags:[`nodejs_compat`],assets:{directory:`./dist/client`,not_found_handling:`none`,binding:`ASSETS`}}}))}function mr(e,t){return e?`${e}/${t}`:t}function hr(e){let t=e.packageManager===`pnpm`?`pnpm-lock.yaml`:`bun.lock`;return B({$schema:`https://railway.com/railway.schema.json`,build:{builder:`DOCKERFILE`,dockerfilePath:mr(e.prefix,`Dockerfile`),watchPatterns:[`.dockerignore`,e.prefix?`${e.prefix}/**`:`src/**`,...e.watchedPackages.map(e=>`packages/${e}/**`),`package.json`,t,...e.prefix?[`tsconfig.base.json`]:[`tsconfig.json`]]},deploy:{...e.preDeployCommand?{preDeployCommand:e.preDeployCommand}:{},healthcheckPath:e.healthcheckPath,healthcheckTimeout:100,restartPolicyType:`ON_FAILURE`,restartPolicyMaxRetries:10}})}function gr(e){if(!e.monorepo)return B({$schema:`https://openapi.vercel.sh/vercel.json`,framework:`nextjs`});let t=e.filter??`web`;return e.packageManager===`pnpm`?B({$schema:`https://openapi.vercel.sh/vercel.json`,framework:`nextjs`,installCommand:`cd ../.. && pnpm install --frozen-lockfile`,buildCommand:`cd ../.. && pnpm exec turbo run build --filter=${t}`}):B({$schema:`https://openapi.vercel.sh/vercel.json`,framework:`nextjs`,installCommand:`cd ../.. && curl -fsSL https://bun.com/install | BUN_INSTALL=$PWD/.bun bash && $PWD/.bun/bin/bun install --frozen-lockfile`,buildCommand:`cd ../.. && BUN_INSTALL=$PWD/.bun PATH=$PWD/.bun/bin:$PATH bunx turbo run build --filter=${t}`})}function _r(e){let t=[];return e.railway&&t.push({path:mr(e.railwayOptions.prefix,`railway.json`),content:hr(e.railwayOptions)}),e.vercel&&t.push({path:mr(e.webPrefix,`vercel.json`),content:gr(e.vercelOptions)}),t}const vr=/^[ \t]*(?:\/\/|#|\{\/\*|<!--)[ \t]*#(if|else|endif)\b[ \t]*([!A-Za-z0-9_-]*)[ \t]*(?:\*\/\}|-->)?[ \t]*$/,yr=/__ROCK_[A-Z0-9_]+__/g;function br(e,t){if(!e)throw Error(`Diretiva #if sem feature.`);return e.startsWith(`!`)?!t.has(e.slice(1)):t.has(e)}function xr(e,t){return e.replace(yr,e=>{let n=t[e];if(n===void 0)throw Error(`Token de template desconhecido: ${e}`);return n})}function Sr(e,t){let n=e.split(`
|
|
216
|
+
`),r=[],i=[];for(let[e,a]of n.entries()){let n=vr.exec(a);if(!n){(i.length===0||i[i.length-1]?.active)&&r.push(a);continue}let[,o,s=``]=n,c=i[i.length-1];if(o===`if`){let e=!c||c.active,n=br(s,t);i.push({active:e&&n,parentActive:e,matched:n,seenElse:!1})}else{if(!c)throw Error(`Diretiva #${o} sem #if correspondente na linha ${e+1}.`);if(o===`else`){if(c.seenElse)throw Error(`Segundo #else no mesmo bloco na linha ${e+1}.`);c.seenElse=!0,c.active=c.parentActive&&!c.matched}else i.pop()}}if(i.length>0)throw Error(`Diretiva #if sem #endif correspondente.`);return xr(r.join(`
|
|
217
|
+
`),t.tokens)}function Cr(e){let t=e.split(`/`).map(e=>e.startsWith(`dot-`)?`.${e.slice(4)}`:e),n=t[t.length-1]??``;return n.endsWith(`.tpl`)&&(t[t.length-1]=n.slice(0,-4)),t.join(`/`)}function U(e,t){return e.entries.filter(e=>!e.condition||e.condition(t)).map(n=>{let r=c.posix.join(e.dir,n.source),i=n.target??Cr(n.source);return{path:e.prefix?c.posix.join(e.prefix,i):i,content:Sr(Jn(r),t)}})}const wr=`franchising`,Tr=`^0.7.0`,Er={[wr]:Tr},Dr={"@opentelemetry/api":`^1.9.0`,"@opentelemetry/api-logs":`^0.208.0`,"@opentelemetry/auto-instrumentations-node":`^0.67.0`,"@opentelemetry/exporter-logs-otlp-http":`^0.208.0`,"@opentelemetry/exporter-metrics-otlp-http":`^0.208.0`,"@opentelemetry/exporter-trace-otlp-http":`^0.208.0`,"@opentelemetry/resources":`^2.0.0`,"@opentelemetry/sdk-logs":`^0.208.0`,"@opentelemetry/sdk-metrics":`^2.0.0`,"@opentelemetry/sdk-node":`^0.208.0`,"nestjs-pino":`^4.4.0`,pino:`^9.7.0 || ^10.0.0`},Or={betterstack:{"@sentry/node":`^9.0.0`},posthog:{"posthog-node":`^5.52.4`}},kr={jose:`^6.2.12`,zod:`^4.6.7`},Ar={"class-variance-authority":`^0.7.1`,cmdk:`^1.1.1`,cnfast:`0.1.0`,"input-otp":`^1.5.0`,"lucide-react":`^0.469.0`,"radix-ui":`^1.6.7`,"react-day-picker":`^10.0.1`,sonner:`^2.0.7`,"sugar-high":`^2.4.1`,vaul:`^1.1.2`};function jr(e){return e===`betterstack`?` BETTERSTACK_OTLP_ENDPOINT: str({ devDefault: '' }),
|
|
218
|
+
BETTERSTACK_ERRORS_DSN: str({ devDefault: '' }),
|
|
219
|
+
`:` POSTHOG_API_KEY: str({ devDefault: '' }),
|
|
220
|
+
POSTHOG_HOST: str({ default: 'https://us.i.posthog.com' }),
|
|
221
|
+
`}const Mr=` TELEMETRY_ENABLED: bool({ default: true, devDefault: false }),
|
|
222
|
+
`;function Nr(e){return{...Er,...Dr,...Or[e]}}function Pr(e){return`TELEMETRY_ENABLED="false"
|
|
223
|
+
${e===`betterstack`?`BETTERSTACK_OTLP_ENDPOINT=""
|
|
224
|
+
BETTERSTACK_ERRORS_DSN=""
|
|
225
|
+
`:`POSTHOG_API_KEY=""
|
|
226
|
+
POSTHOG_HOST="https://us.i.posthog.com"
|
|
227
|
+
`}`}const Fr=[{id:`jobs`,description:`Nomes de fila e politica de retentativa compartilhados`,sources:[`src/index.ts`,`src/shared/queue/job-id.ts`,`src/shared/queue/options.ts`,`src/shared/queue/prefix.ts`]},{id:`queue`,sources:[`src/index.ts`,`src/shared/errors/failure-reason.ts`,`src/shared/redis/connection.ts`,`src/types/redis/connection.ts`],description:`Conexoes Redis para produtor e consumidor de fila`,dependencies:{ioredis:`^5.4.1`}},{id:`webhooks`,description:`Segredo cifrado, assinatura Standard Webhooks e URL permitida`,sources:[`src/index.ts`,`src/shared/crypto/secret.ts`,`src/shared/signing/headers.ts`,`src/shared/url/deliverable.ts`,`src/types/webhooks/job.ts`,`test/webhooks.test.ts.tpl`],scripts:{test:`bun test`},dependencies:{standardwebhooks:`^1.1.1`}}];function Ir(e){return H({extends:`../../tsconfig.base.json`,compilerOptions:{module:`CommonJS`,moduleResolution:`node`,target:`ES2023`,declaration:!0,rootDir:`./src`,outDir:`./dist`,types:[`node`]},include:[`src/**/*.ts`],exclude:[`node_modules`,`dist`,...e?[`test`]:[]]})}function Lr(e){return Fr.filter(t=>e.packages.includes(t.id)).flatMap(t=>{let n=`packages/${t.id}`;return[...U({dir:`packages/${t.id}`,prefix:n,entries:t.sources.map(e=>({source:e}))},{has:()=>!1,tokens:{}}),...t.id===`jobs`?[{path:`${n}/src/shared/queue/names.ts`,content:e.queueNames}]:[],{path:`${n}/package.json`,content:V({name:`${e.scope}/${t.id}`,description:t.description,packageManager:e.packageManager,files:[`dist`],main:`./dist/index.js`,types:`./src/index.ts`,exports:{".":{types:`./src/index.ts`,default:`./dist/index.js`}},scripts:{build:`tsc -p tsconfig.build.json`,lint:`ultracite check`,typecheck:`tsc --noEmit -p tsconfig.json`,...t.scripts},dependencies:t.dependencies,devDependencies:{"@types/node":`^24.0.15`,typescript:`^5.9.3`}})},{path:`${n}/tsconfig.json`,content:Ir(!1)},{path:`${n}/tsconfig.build.json`,content:Ir(!0)}]})}function Rr(e){return{has:t=>t===e,tokens:{}}}function zr(e){return U({dir:`observability`,prefix:`${e.prefix}src/shared/observability`,entries:[{source:`local-index.ts`,target:`index.ts`},{source:`adapters.ts`},{source:`register.ts`},{source:`bootstrap.ts`}]},Rr(e.telemetryAdapter))}function Br(e){let t=`packages/observability`,n=`./src/shared/telemetry/register.ts`;return[...U({dir:`observability`,prefix:t,entries:[{source:`index.ts`,target:`src/index.ts`},{source:`env.ts`,target:`src/env.ts`},{source:`adapters.ts`,target:`src/shared/telemetry/adapters.ts`},{source:`register.ts`,target:`src/shared/telemetry/register.ts`},{source:`bootstrap.ts`,target:`src/shared/bootstrap/process.ts`},{source:`lifecycle.ts`,target:`src/shared/jobs/lifecycle.ts`}]},Rr(e.telemetryAdapter)),{path:`${t}/package.json`,content:V({name:`${e.scope}/observability`,description:`Telemetria compartilhada da API e dos workers: adapters, bootstrap e jobs`,packageManager:e.packageManager,files:[`dist`],main:`./dist/index.js`,types:`./src/index.ts`,exports:{".":{types:`./src/index.ts`,default:`./dist/index.js`},"./register":{types:n,default:`./dist/shared/telemetry/register.js`}},extraFields:{typesVersions:{"*":{register:[n]}}},scripts:{build:`tsc -p tsconfig.build.json`,lint:`ultracite check`,typecheck:`tsc --noEmit -p tsconfig.json`},dependencies:{...Nr(e.telemetryAdapter),"@nestjs/common":`^11.1.17`,bullmq:`^5.63.0`,dotenv:`^16.6.1`,envalid:`^8.1.0`,"reflect-metadata":`^0.2.2`,rxjs:`^7.8.2`},devDependencies:{"@types/node":`^24.0.15`,typescript:`^5.9.3`}})},{path:`${t}/tsconfig.json`,content:Ir(!1)},{path:`${t}/tsconfig.build.json`,content:Ir(!0)}]}function Vr(e,t,n){let r=t.hosting;if(!r)return e;let i=new Map(e.map(e=>[e.path,{...e}])),a=n===`monolith`?`apps/api/`:``,o=n===`monolith`?`apps/web/`:``,s=e=>i.get(e)?.content??``,c=(e,t)=>i.set(e,{path:e,content:t}),l=(e,t)=>{let n=JSON.parse(s(e));t(n),c(e,B(n))},u=r.api===`cloudflare`&&n!==`web`,d=r.web===`cloudflare`&&n!==`api`,f=r.webType===`landing`&&!t.features.betterAuth,p=d&&r.webAdapter!==`opennext`,m=Object.fromEntries(t.workers.map((e,t)=>[e.queue,`JOBS_${t}`])),h=t.workers.map(e=>`${t.projectSlug}-${e.queue}`);if(u){i.delete(`${a}Dockerfile`),i.delete(`${a}railway.json`);for(let e of i.keys())(e.startsWith(`apps/workers/`)||e.startsWith(`packages/queue/`)||e.startsWith(`packages/jobs/`))&&i.delete(e);let e=i.get(`packages/observability/package.json`);if(e?.content){let n=JSON.parse(e.content).name;for(let e of i.keys())e.startsWith(`packages/observability/`)&&i.delete(e);for(let e of zr({prefix:a,telemetryAdapter:t.telemetryAdapter}))i.set(e.path,e);for(let e of i.keys())e.startsWith(`${a}src/`)&&e.endsWith(`.ts`)&&c(e,s(e).replaceAll(`'${n}`,`'./shared/observability`));l(`${a}package.json`,e=>{delete e.dependencies?.[n]}),l(`package.json`,e=>{for(let[t,r]of Object.entries(e.scripts))e.scripts[t]=r.split(` && `).filter(e=>!e.includes(`${n} `)).join(` && `)})}l(`${a}package.json`,e=>{e.type=`module`,e.dependencies={...e.dependencies,pg:`^8.16.3`,unenv:`2.0.0-rc.24`},delete e.dependencies.ioredis,delete e.dependencies[`@${t.projectSlug}/cache`],e.devDependencies={...e.devDependencies,wrangler:`^4.0.0`,"@cloudflare/workers-types":`^5.20261005.1`,"@types/pg":`^8.15.5`};let r=n===`api`&&t.databaseOrm!==`drizzle`?`prisma generate && `:``;e.scripts[`cf:compile`]=`${r}nest build`,e.scripts.build=`wrangler deploy --dry-run --outdir .worker-build`,e.scripts.dev=`wrangler dev --port 3001`,e.scripts.deploy=`wrangler deploy`,e.scripts.preview=`wrangler dev --port 3001`,e.scripts.start=e.scripts.preview,e.scripts[`start:dev`]=e.scripts.dev,e.scripts[`start:prod`]=e.scripts.deploy});let o=JSON.parse(s(`${a}tsconfig.json`));o.compilerOptions.module=`ESNext`,o.compilerOptions.moduleResolution=`bundler`,o.compilerOptions.types=[`node`,`@cloudflare/workers-types`],c(`${a}tsconfig.json`,B(o)),c(`${a}.swcrc`,B({jsc:{parser:{syntax:`typescript`,decorators:!0},target:`es2022`,transform:{legacyDecorator:!0,decoratorMetadata:!0}},module:{type:`es6`},sourceMaps:!0}));let u=s(`${a}src/main.ts`),d=u.indexOf(` await app.listen(`);if(d<0)throw Error(`Bootstrap NestJS inesperado no template.`);c(`${a}src/main.ts`,u.slice(0,d).replace(`Logger, ValidationPipe`,`ValidationPipe`).replace(`async function bootstrap()`,`export async function createApplication(): Promise<NestFastifyApplication>`).replace(` app.enableShutdownHooks();`,``).replace(`{ bodyParser: false }`,`{ bodyParser: false, abortOnError: false }`).replace(`{ bodyParser: false, bufferLogs: true }`,`{ bodyParser: false, bufferLogs: true, abortOnError: false }`)+` try {
|
|
215
228
|
await app.init();
|
|
216
229
|
await app.getHttpAdapter().getInstance().ready();
|
|
230
|
+
|
|
217
231
|
return app;
|
|
218
232
|
} catch (error) {
|
|
219
233
|
await app.close();
|
|
220
234
|
throw error;
|
|
221
235
|
}
|
|
222
236
|
}
|
|
223
|
-
`);let
|
|
224
|
-
`+
|
|
237
|
+
`);let f=Jn(`cloudflare/worker.ts`);t.workers.length&&(f=`import { processJob, type Job } from './modules/queue/service';
|
|
238
|
+
`+f,f=f.replace(`export default {`,`export default {\n async queue(batch: MessageBatch<Job>): Promise<void> {\n const names = ${JSON.stringify(Object.fromEntries(t.workers.map((e,t)=>[h[t],e.queue])))};\n const queue = names[batch.queue as keyof typeof names];\n\n if (!queue) throw new Error('Unknown queue.');\n\n await Promise.all(batch.messages.map(async (message) => {\n try { await processJob(queue, message.body); message.ack(); }\n catch { message.retry(); }\n }));\n },`),c(`${a}src/modules/queue/service.ts`,Jn(`cloudflare/queue.service.ts`).replace(`__ROCK_QUEUE_BINDINGS__`,JSON.stringify(m))),c(`${a}src/modules/queue/module.ts`,`import { Global, Module } from '@nestjs/common';
|
|
225
239
|
import { QueueService } from './service';
|
|
226
240
|
@Global()
|
|
227
241
|
@Module({ providers: [QueueService], exports: [QueueService] })
|
|
228
242
|
export class QueueModule {}
|
|
229
243
|
`),c(`${a}src/app.module.ts`,`import { QueueModule } from './modules/queue/module';
|
|
230
|
-
`+s(`${a}src/app.module.ts`).replace(`CacheModule,`,`QueueModule, CacheModule,`))),c(`${a}src/worker.ts`,
|
|
231
|
-
`,``).replace(`desc: 'PostgreSQL connection string',`,`default: '${
|
|
244
|
+
`+s(`${a}src/app.module.ts`).replace(`CacheModule,`,`QueueModule, CacheModule,`))),c(`${a}src/worker.ts`,f),c(`${a}src/modules/cache/cache.service.ts`,Jn(`cloudflare/cache.service.ts`)),c(`${a}src/env.ts`,ur(s(`${a}src/env.ts`)).replace(`import 'dotenv/config';
|
|
245
|
+
`,``).replace(`desc: 'PostgreSQL connection string',`,`default: '${lr}',`));for(let e of[`${a}.env`,`${a}.env.example`])c(e,ur(s(e)));c(`${a}.dev.vars.example`,s(`${a}.env.example`)+`
|
|
232
246
|
# Copy to .dev.vars; use wrangler secret put for production secrets.
|
|
233
|
-
`);let
|
|
247
|
+
`);let p=n===`monolith`?`packages/database/`:a;if(c(n===`monolith`?`${p}src/database.service.ts`:`${a}src/modules/database/database.service.ts`,dr(t.databaseOrm===`drizzle`,n===`api`)),n===`monolith`){for(let e of[`.env`,`.env.example`])c(`packages/database/${e}`,`DATABASE_URL="${lr}"\n`);c(`packages/database/src/env.ts`,ur(s(`packages/database/src/env.ts`))),c(`${a}src/modules/database/database.service.ts`,s(`${a}src/modules/database/database.service.ts`).replace(` async connect()`,` get client() { return this.database.client; }
|
|
234
248
|
|
|
235
|
-
async connect()`)),i.has(`${a}src/auth.ts`)&&c(`${a}src/auth.ts`,s(`${a}src/auth.ts`).replace(`from '@${t.projectSlug}/database'`,`from './modules/database/database.service'`));let e=`${a}src/modules/auth/auth.module.ts`;i.has(e)&&c(e,s(e).replace(`from '@${t.projectSlug}/database'`,`from '../database/database.service'`));let n=JSON.parse(s(`packages/database/tsconfig.build.json`));n.compilerOptions.module=`ESNext`,n.compilerOptions.moduleResolution=`bundler`,n.compilerOptions.types=[`node`,`@cloudflare/workers-types`],c(`packages/database/tsconfig.build.json`,
|
|
249
|
+
async connect()`)),i.has(`${a}src/auth.ts`)&&c(`${a}src/auth.ts`,s(`${a}src/auth.ts`).replace(`from '@${t.projectSlug}/database'`,`from './modules/database/database.service'`));let e=`${a}src/modules/auth/auth.module.ts`;i.has(e)&&c(e,s(e).replace(`from '@${t.projectSlug}/database'`,`from '../database/database.service'`));let n=JSON.parse(s(`packages/database/tsconfig.build.json`));n.compilerOptions.module=`ESNext`,n.compilerOptions.moduleResolution=`bundler`,n.compilerOptions.types=[`node`,`@cloudflare/workers-types`],c(`packages/database/tsconfig.build.json`,B(n)),c(`packages/cache/src/cache.service.ts`,Jn(`cloudflare/cache.service.ts`).replace(`import { Injectable } from '@nestjs/common';
|
|
236
250
|
`,``).replace(`@Injectable()
|
|
237
251
|
`,``)),c(`packages/cache/src/env.ts`,`export const env = {};
|
|
238
|
-
`),l(`packages/cache/package.json`,e=>{delete e.dependencies?.ioredis,e.devDependencies={...e.devDependencies,"@cloudflare/workers-types":`^5.20261005.1`}});let r=JSON.parse(s(`packages/cache/tsconfig.build.json`));r.compilerOptions.module=`ESNext`,r.compilerOptions.moduleResolution=`bundler`,r.compilerOptions.types=[`node`,`@cloudflare/workers-types`],c(`packages/cache/tsconfig.build.json`,
|
|
239
|
-
engineType = "client"`)),t.features.betterAuth&&(c(`${a}src/auth.ts`,s(`${a}src/auth.ts`).replace(`import { DatabaseService }`,`import type { DatabaseService }`)),c(`${a}auth.config.ts`,
|
|
252
|
+
`),l(`packages/cache/package.json`,e=>{delete e.dependencies?.ioredis,e.devDependencies={...e.devDependencies,"@cloudflare/workers-types":`^5.20261005.1`}});let r=JSON.parse(s(`packages/cache/tsconfig.build.json`));r.compilerOptions.module=`ESNext`,r.compilerOptions.moduleResolution=`bundler`,r.compilerOptions.types=[`node`,`@cloudflare/workers-types`],c(`packages/cache/tsconfig.build.json`,B(r))}l(`${p}package.json`,e=>{e.dependencies={...e.dependencies,pg:`^8.16.3`,...t.databaseOrm===`drizzle`?{}:{"@prisma/adapter-pg":`^6.15.0`}},delete e.dependencies.postgres,e.devDependencies={...e.devDependencies,"@types/pg":`^8.15.5`,"@cloudflare/workers-types":`^5.20261005.1`},t.databaseOrm!==`drizzle`&&(e.dependencies[`@prisma/client`]=`^6.16.0`,e.dependencies[`@prisma/adapter-pg`]=`^6.16.0`,e.devDependencies.prisma=`^6.16.0`)}),t.databaseOrm!==`drizzle`&&c(`${p}prisma/schema.prisma`,s(`${p}prisma/schema.prisma`).replace(`provider = "prisma-client-js"`,`provider = "prisma-client-js"
|
|
253
|
+
engineType = "client"`)),t.features.betterAuth&&(c(`${a}src/auth.ts`,s(`${a}src/auth.ts`).replace(`import { DatabaseService }`,`import type { DatabaseService }`)),t.databaseOrm!==`drizzle`&&c(`${a}auth.config.ts`,or(!1,n===`monolith`,t.projectSlug,t.messaging)),l(`${a}package.json`,e=>{let r=n===`monolith`?`../../packages/database/`:`./`,i=t.databaseOrm===`drizzle`?`${r}src/${n===`monolith`?``:`modules/database/`}schema.ts`:`${r}prisma/schema.prisma`,a=n===`monolith`?`${z(t.packageManager,`@${t.projectSlug}/database`,t.databaseOrm===`drizzle`?`build`:`db:generate`)} && `:t.databaseOrm===`drizzle`?``:`prisma generate && `;e.dependencies={...e.dependencies,...t.databaseOrm===`drizzle`?{"drizzle-orm":`^0.44.4`}:{"@prisma/client":`^6.16.0`,"@prisma/adapter-pg":`^6.16.0`}},t.databaseOrm!==`drizzle`&&(e.scripts[`auth:generate`]=`${a}auth generate --config ./auth.config.ts --output ${i}`,e.devDependencies={...e.devDependencies,auth:`^1.6.20`})})),c(`${a}wrangler.jsonc`,B({$schema:`node_modules/wrangler/config-schema.json`,name:`${t.projectSlug}-api`,main:`dist/worker.js`,build:{command:`${t.packageManager} run cf:compile`,watch_dir:`src`},compatibility_date:sr,compatibility_flags:[`nodejs_compat`],alias:{"@nestjs/platform-express":`unenv/mock/empty`,"@fastify/view":`unenv/mock/empty`,"class-transformer/storage":`class-transformer/cjs/storage.js`,"@nestjs/microservices":`unenv/mock/empty`,"@nestjs/microservices/microservices-module":`unenv/mock/empty`,"@nestjs/websockets/socket-module":`unenv/mock/empty`},vars:{API_URL:`http://localhost:3001`,CLIENT_ORIGIN:`http://localhost:3000`,API_DOCS_ENABLED:!0},hyperdrive:[{binding:`HYPERDRIVE`,id:`00000000000000000000000000000000`,localConnectionString:lr}],...r.kv?{kv_namespaces:[{binding:`CACHE`,id:`00000000000000000000000000000000`}]}:{},...t.workers.length?{queues:{producers:t.workers.map((e,t)=>({binding:m[e.queue],queue:h[t]})),consumers:h.map(e=>({queue:e,max_batch_size:10,max_retries:3}))}}:{}})),c(`docker-compose.yml`,fr()),c(`infra/cloudflared/Dockerfile`,`FROM cloudflare/cloudflared:latest
|
|
240
254
|
CMD ["tunnel", "--no-autoupdate", "run"]
|
|
241
|
-
`),c(`infra/cloudflared/railway.json`,
|
|
255
|
+
`),c(`infra/cloudflared/railway.json`,B({$schema:`https://railway.com/railway.schema.json`,build:{builder:`DOCKERFILE`,dockerfilePath:`infra/cloudflared/Dockerfile`,watchPatterns:[`infra/cloudflared/**`]},deploy:{restartPolicyType:`ON_FAILURE`,restartPolicyMaxRetries:10}})),c(`infra/cloudflared/.env.example`,`# Railway service variables; configure through Railway, never commit values.
|
|
242
256
|
TUNNEL_TOKEN=
|
|
243
|
-
`)}if(n!==`api`&&f&&(c(`${o}next.config.mjs`,`export default { reactStrictMode: true, output: "export", ${p?`trailingSlash: true, `:``}images: { unoptimized: true } };\n`),l(`${o}package.json`,e=>{d?e.scripts.start=`wrangler pages dev out --port 3000`:(e.devDependencies={...e.devDependencies,serve:`^14.2.4`},e.scripts.start=`serve out --listen 3000`)})),p?(i.delete(`${o}Dockerfile`),i.delete(`${o}vercel.json`),
|
|
257
|
+
`)}if(n!==`api`&&f&&(c(`${o}next.config.mjs`,`export default { reactStrictMode: true, output: "export", ${p?`trailingSlash: true, `:``}images: { unoptimized: true } };\n`),l(`${o}package.json`,e=>{d?e.scripts.start=`wrangler pages dev out --port 3000`:(e.devDependencies={...e.devDependencies,serve:`^14.2.4`},e.scripts.start=`serve out --listen 3000`)})),p?(i.delete(`${o}Dockerfile`),i.delete(`${o}vercel.json`),pr(t,o,f,s,c,l)):d?(i.delete(`${o}Dockerfile`),i.delete(`${o}vercel.json`),l(`${o}package.json`,e=>{e.devDependencies={...e.devDependencies,wrangler:`^4.0.0`,"@cloudflare/workers-types":`^5.20261005.1`},f?(e.scripts.preview=`next build && wrangler pages dev out --port 3000`,e.scripts.deploy=`next build && wrangler pages deploy out --project-name ${t.projectSlug}-web`):(e.devDependencies[`@opennextjs/cloudflare`]=`^1.0.0`,e.scripts.preview=`opennextjs-cloudflare build && opennextjs-cloudflare preview`,e.scripts.deploy=`opennextjs-cloudflare build && opennextjs-cloudflare deploy`,e.scripts[`cf:typegen`]=`wrangler types --env-interface CloudflareEnv cloudflare-env.d.ts`)}),c(`${o}wrangler.jsonc`,B({$schema:`node_modules/wrangler/config-schema.json`,name:`${t.projectSlug}-web`,compatibility_date:sr,...f?{pages_build_output_dir:`./out`}:{main:`.open-next/worker.js`,compatibility_flags:[`nodejs_compat`],assets:{directory:`.open-next/assets`,binding:`ASSETS`},services:[{binding:`WORKER_SELF_REFERENCE`,service:`${t.projectSlug}-web`}]}})),f||(c(`${o}open-next.config.ts`,`import { defineCloudflareConfig } from '@opennextjs/cloudflare';
|
|
244
258
|
export default defineCloudflareConfig();
|
|
245
259
|
`),c(`${o}next.config.mjs`,`import { initOpenNextCloudflareForDev } from '@opennextjs/cloudflare';
|
|
246
260
|
initOpenNextCloudflareForDev();
|
|
247
|
-
`+s(`${o}next.config.mjs`)))):r.web===`vercel`&&n===`web`&&c(`vercel.json`,
|
|
261
|
+
`+s(`${o}next.config.mjs`)))):r.web===`vercel`&&n===`web`&&c(`vercel.json`,gr({packageManager:t.packageManager,monorepo:!1})),u||d){if(n===`monolith`){c(`${o}src/env.ts`,s(`${o}src/env.ts`).replaceAll(`http://localhost:3000`,`http://localhost:3001`));for(let e of[`.env`,`.env.example`])c(`${o}${e}`,s(`${o}${e}`)+`NEXT_PUBLIC_API_URL="http://localhost:3001"
|
|
248
262
|
NEXT_PUBLIC_AUTH_URL="http://localhost:3001"
|
|
249
|
-
`);for(let e of[`src/
|
|
263
|
+
`);for(let e of[`src/shared/auth/client.ts`,`src/shared/auth/server.ts`])i.has(`${o}${e}`)&&c(`${o}${e}`,s(`${o}${e}`).replaceAll(`/api/auth`,`/v1/auth`))}c(`.gitignore`,s(`.gitignore`)+`
|
|
250
264
|
# Cloudflare
|
|
251
265
|
**/.wrangler/
|
|
252
266
|
**/.worker-build/
|
|
@@ -257,52 +271,244 @@ NEXT_PUBLIC_AUTH_URL="http://localhost:3001"
|
|
|
257
271
|
!**/.dev.vars.example
|
|
258
272
|
`+(p?`**/dist/
|
|
259
273
|
**/.vinext/
|
|
260
|
-
`:``)),n===`monolith`&&l(`package.json`,e=>{u&&(e.scripts[`deploy:api`]=`cd apps/api && ${t.packageManager} run deploy`),d&&(e.scripts[`deploy:web`]=`cd apps/web && ${t.packageManager} run deploy`)})}return[...i.values()]}const
|
|
274
|
+
`:``)),n===`monolith`&&l(`package.json`,e=>{u&&(e.scripts[`deploy:api`]=`cd apps/api && ${t.packageManager} run deploy`),d&&(e.scripts[`deploy:web`]=`cd apps/web && ${t.packageManager} run deploy`)})}return[...i.values()]}const Hr=`node:22.23.4-alpine3.24`,Ur=`oven/bun:${Xn}-alpine`,Wr=3001,Gr=3e3,Kr={api:`API NestJS`,worker:`Worker BullMQ (sem HTTP: so consome filas)`,web:`Website Next.js em modo standalone`};function qr(e){return e.packageManager===`pnpm`?`pnpm-lock.yaml`:`bun.lock`}function Jr(e,t,n){return[`# syntax=docker/dockerfile:1.7`,`# ${Kr[e.kind]}.`,t.monorepo?`# Build a partir da raiz do monorepo: docker build -f ${e.dir}Dockerfile .`:`# Build na raiz do projeto: docker build .`,`#`,`# Estagios, do mais estavel ao mais volatil, para o cache durar:`,...n.map(e=>`# ${e}`),`# Mudar so o codigo refaz o build e as ultimas camadas, nunca o`,"# node_modules. `--ignore-scripts` em todo install: os scripts de",`# install (prisma generate, lefthook) dependem de pacote de`,`# desenvolvimento ou do .git, e o build roda o que precisa.`,``].join(`
|
|
275
|
+
`)}function Yr(e){return e?`ENV NODE_ENV=production`:`ENV NODE_ENV=production \\
|
|
276
|
+
# Cache de compilacao do V8 entre execucoes do mesmo conteiner: o
|
|
277
|
+
# segundo boot (restart, pre-deploy seguido do start) sobe mais rapido.
|
|
278
|
+
NODE_COMPILE_CACHE=/tmp/node-compile-cache \\
|
|
279
|
+
# Stack com arquivo e linha do TypeScript (os \`.map\` vem no dist).
|
|
280
|
+
NODE_OPTIONS=--enable-source-maps`}function Xr(e){let t=e.packageManagerVersion.replace(/^pnpm@/,``);return`FROM ${Hr} AS base
|
|
281
|
+
ENV CI=1 \\
|
|
282
|
+
COREPACK_ENABLE_STRICT=0
|
|
283
|
+
# pnpm pelo npm, na versao do \`packageManager\` da raiz. (O corepack falha no
|
|
284
|
+
# builder da Railway ao conferir a assinatura do pacote.)
|
|
285
|
+
RUN npm install -g pnpm@${t} --no-fund --no-audit \\
|
|
286
|
+
&& npm cache clean --force \\
|
|
287
|
+
&& pnpm config set prefer-offline true
|
|
288
|
+
WORKDIR /app
|
|
289
|
+
`}function Zr(){return`FROM ${Ur} AS base
|
|
290
|
+
ENV CI=1
|
|
291
|
+
WORKDIR /app
|
|
292
|
+
`}function Qr(e,t){return e.kind===`web`?t.monorepo?`["node", "${e.dir}server.js"]`:`["node", "server.js"]`:t.runtime===`bun`?`["bun", "src/main.ts"]`:`["node", "dist/main.js"]`}function $r(e,t,n){return`# O client do Prisma e gerado para o node_modules de producao; o do build
|
|
293
|
+
# fica para tras junto com as dependencias de desenvolvimento.
|
|
294
|
+
RUN cd ${t||`.`} && ${n?`bunx`:`npx --yes`} prisma@${e.prismaRange} generate --schema prisma/schema.prisma${n?``:` \\
|
|
295
|
+
&& rm -rf /root/.npm`}
|
|
296
|
+
`}function ei(e,t){return!(!e.databaseDir||e.kind!==`api`&&t.databaseOrm!==`prisma`)}function ti(e,t){let n=e.packages.map(e=>c.posix.basename(e)),r=e.packages.map(e=>`COPY ${e}/package.json ${e}/`).join(`
|
|
297
|
+
`),i=e.packages.map(e=>`COPY ${e} ${e}`).join(`
|
|
298
|
+
`),a=ei(e,t)?c.posix.basename(e.databaseDir??``):void 0,o=t.databaseOrm===`prisma`?`prisma`:`drizzle`;return`${Jr(e,t,[`deps baixa os pacotes do lockfile para o store do pnpm`,`manifests package.json desta app e dos packages que ela usa`,`prod-deps node_modules de producao, so a partir dos manifests`,`build dependencias de desenvolvimento + codigo + build`,`overlay codigo compilado nos caminhos reais do node_modules`,`runner node_modules de producao + o codigo compilado por cima`,"`prod-deps` e `build` nao dependem um do outro e rodam em paralelo."])}
|
|
299
|
+
${Xr(t)}
|
|
300
|
+
# Download guiado so pelo lockfile: aquece o store uma vez, antes de
|
|
301
|
+
# \`prod-deps\` e \`build\` rodarem em paralelo.
|
|
302
|
+
FROM base AS deps
|
|
303
|
+
COPY pnpm-lock.yaml pnpm-workspace.yaml ./
|
|
304
|
+
RUN pnpm fetch --frozen-lockfile
|
|
305
|
+
|
|
306
|
+
# So entram esta app e os packages de que ela depende.
|
|
307
|
+
FROM deps AS manifests
|
|
308
|
+
COPY package.json ./
|
|
309
|
+
COPY ${e.dir}package.json ${e.dir}
|
|
310
|
+
${r}
|
|
261
311
|
|
|
262
|
-
|
|
263
|
-
|
|
312
|
+
FROM manifests AS prod-deps
|
|
313
|
+
# Pacote autocontido so com dependencias de producao; os packages do
|
|
314
|
+
# workspace entram copiados (o codigo compilado deles chega no overlay).
|
|
315
|
+
RUN pnpm --filter ${e.name} deploy --prod --ignore-scripts \\
|
|
316
|
+
--config.inject-workspace-packages=true /out
|
|
317
|
+
|
|
318
|
+
FROM manifests AS build
|
|
319
|
+
RUN pnpm install --frozen-lockfile --ignore-scripts --filter "${e.name}..."
|
|
320
|
+
# O tsconfig e o codigo so entram depois do install: mudar um deles nao
|
|
321
|
+
# refaz o node_modules.
|
|
322
|
+
COPY tsconfig.base.json ./
|
|
323
|
+
${i}
|
|
324
|
+
COPY ${e.dir.slice(0,-1)} ${e.dir.slice(0,-1)}
|
|
325
|
+
${a?`# A pasta de migrations pode ainda nao existir num projeto novo.\nRUN mkdir -p ${e.databaseDir}/${o}\n`:``}# \`-r\` segue a ordem das dependencias e roda em paralelo o que e independente.
|
|
326
|
+
RUN pnpm --filter "${e.name}..." -r run build
|
|
327
|
+
|
|
328
|
+
# Monta o codigo compilado nos caminhos reais do node_modules de producao
|
|
329
|
+
# (os packages do workspace ficam em \`.pnpm/<nome>@file.../\`). Sai uma arvore
|
|
330
|
+
# pequena, sem symlinks no caminho, para o runner copiar por cima.
|
|
331
|
+
FROM prod-deps AS overlay
|
|
332
|
+
COPY --from=build /app/${e.dir}dist /overlay/dist
|
|
333
|
+
COPY --from=build /app/packages /build/packages
|
|
334
|
+
# Cada package pode estar injetado mais de uma vez (dependencia direta e de
|
|
335
|
+
# outro package): todas as copias recebem o codigo compilado.
|
|
336
|
+
RUN for pkg in ${n.join(` `)}; do \\
|
|
337
|
+
name=$(node -p "require('/build/packages/$pkg/package.json').name"); \\
|
|
338
|
+
for target in /out/node_modules/.pnpm/$(echo "$name" | tr / +)@file*/node_modules/$name; do \\
|
|
339
|
+
[ -d "$target" ] || continue; \\
|
|
340
|
+
mkdir -p "/overlay\${target#/out}"; \\
|
|
341
|
+
cp -r "/build/packages/$pkg/dist" "/overlay\${target#/out}/"; \\
|
|
342
|
+
${a?` # Migrations do pre-deploy.\n if [ "$pkg" = ${a} ]; then \\\n cp -r /build/packages/${a}/${o} "/overlay\${target#/out}/"; \\\n fi; \\\n`:``} done; \\
|
|
343
|
+
done
|
|
344
|
+
|
|
345
|
+
FROM ${Hr} AS runner
|
|
346
|
+
${Yr(!1)}
|
|
347
|
+
WORKDIR /app
|
|
348
|
+
COPY --from=prod-deps /out ./
|
|
349
|
+
# Codigo compilado por cima, numa camada pequena. Fica com o root: o
|
|
350
|
+
# processo le, mas nao consegue alterar o proprio codigo.
|
|
351
|
+
COPY --from=overlay /overlay ./
|
|
352
|
+
${e.databaseName&&t.databaseOrm===`prisma`?$r(t,`node_modules/${e.databaseName}`,!1):``}USER node
|
|
353
|
+
${e.kind===`api`?`EXPOSE ${Wr}\n`:``}# Processo direto como PID 1: a app trata o SIGTERM (\`enableShutdownHooks\`)
|
|
354
|
+
# e encerra limpo no redeploy.
|
|
355
|
+
CMD ${Qr(e,t)}
|
|
356
|
+
`}function ni(e,t,n){let r=t.runtime===`bun`,i=[...e.packages,...r?[]:[e.dir.slice(0,-1)]].map(e=>`RUN cd ${e} && bun run build`),a=ei(e,t)?e.databaseDir:void 0,o=t.databaseOrm===`prisma`?`prisma`:`drizzle`;return`${Jr(e,t,[`manifests package.json de todos os workspaces e o lockfile`,`prod-deps node_modules de producao`,`build dependencias de desenvolvimento + codigo + build`,`runner node_modules de producao + o codigo compilado por cima`,"`prod-deps` e `build` nao dependem um do outro e rodam em paralelo."])}
|
|
357
|
+
${Zr()}
|
|
358
|
+
# O Bun confere o lockfile contra todos os workspaces: entram os package.json
|
|
359
|
+
# de todos, nao so os desta app. O \`--filter\` limita o que e instalado.
|
|
360
|
+
FROM base AS manifests
|
|
361
|
+
COPY package.json bun.lock ./
|
|
362
|
+
${n.map(e=>`COPY ${e}/package.json ${e}/`).join(`
|
|
363
|
+
`)}
|
|
364
|
+
|
|
365
|
+
FROM manifests AS prod-deps
|
|
366
|
+
RUN bun install --frozen-lockfile --production --ignore-scripts --filter ${e.name}
|
|
367
|
+
|
|
368
|
+
FROM manifests AS build
|
|
369
|
+
RUN bun install --frozen-lockfile --ignore-scripts --filter ${e.name}
|
|
370
|
+
# O tsconfig e o codigo so entram depois do install: mudar um deles nao
|
|
371
|
+
# refaz o node_modules.
|
|
372
|
+
COPY tsconfig.base.json ./
|
|
373
|
+
${e.packages.map(e=>`COPY ${e} ${e}`).join(`
|
|
374
|
+
`)}
|
|
375
|
+
COPY ${e.dir.slice(0,-1)} ${e.dir.slice(0,-1)}
|
|
376
|
+
${a?`# A pasta de migrations pode ainda nao existir num projeto novo.\nRUN mkdir -p ${a}/${o}\n`:``}# Na ordem das dependencias: cada package compila contra o dist do anterior.
|
|
377
|
+
${i.join(`
|
|
378
|
+
`)}
|
|
379
|
+
|
|
380
|
+
FROM ${r?Ur:Hr} AS runner
|
|
381
|
+
${Yr(r)}
|
|
382
|
+
WORKDIR /app
|
|
383
|
+
COPY --from=prod-deps /app ./
|
|
384
|
+
# Os workspaces sao symlinks para estas pastas: o codigo compilado entra
|
|
385
|
+
# nelas, por cima dos package.json que o install ja trouxe.
|
|
386
|
+
${e.packages.map(e=>`COPY --from=build /app/${e}/dist ${e}/dist`).join(`
|
|
387
|
+
`)}
|
|
388
|
+
${a?`COPY --from=build /app/${a}/${o} ${a}/${o}\n`:``}${r?`COPY --from=build /app/tsconfig.base.json ./\nCOPY --from=build /app/${e.dir}src ${e.dir}src\nCOPY --from=build /app/${e.dir}tsconfig.json ${e.dir}`:`COPY --from=build /app/${e.dir}dist ${e.dir}dist`}
|
|
389
|
+
${a&&t.databaseOrm===`prisma`?$r(t,a,r):``}WORKDIR /app/${e.dir.slice(0,-1)}
|
|
390
|
+
USER ${r?`bun`:`node`}
|
|
391
|
+
${e.kind===`api`?`EXPOSE ${Wr}\n`:``}# Processo direto como PID 1: a app trata o SIGTERM (\`enableShutdownHooks\`)
|
|
392
|
+
# e encerra limpo no redeploy.
|
|
393
|
+
CMD ${Qr(e,t)}
|
|
394
|
+
`}function ri(e,t){let n=t.packageManager===`pnpm`,r=t.runtime===`bun`,i=t.databaseOrm===`prisma`?`prisma`:`drizzle`,a=n?`pnpm install --frozen-lockfile --offline --ignore-scripts`:`bun install --frozen-lockfile --ignore-scripts`,o=n?`pnpm install --prod --frozen-lockfile --offline --ignore-scripts`:`bun install --frozen-lockfile --production --ignore-scripts`;return`${Jr(e,t,[`deps ${n?`baixa os pacotes do lockfile para o store do pnpm`:`manifest e lockfile`}`,`prod-deps node_modules de producao`,`build dependencias de desenvolvimento + codigo + build`,`runner node_modules de producao + o codigo compilado`,"`prod-deps` e `build` nao dependem um do outro e rodam em paralelo."])}
|
|
395
|
+
${n?Xr(t):Zr()}
|
|
396
|
+
FROM base AS deps
|
|
397
|
+
COPY package.json ${qr(t)} ./
|
|
398
|
+
${n?`RUN pnpm fetch --frozen-lockfile
|
|
399
|
+
`:``}
|
|
400
|
+
FROM deps AS prod-deps
|
|
401
|
+
RUN ${o}
|
|
402
|
+
|
|
403
|
+
FROM deps AS build
|
|
404
|
+
RUN ${a}
|
|
405
|
+
# O codigo so entra depois do install: mudar o codigo nao refaz o
|
|
406
|
+
# node_modules. O .dockerignore deixa de fora o que o build nao usa.
|
|
407
|
+
COPY . .
|
|
408
|
+
# A pasta de migrations pode ainda nao existir num projeto novo.
|
|
409
|
+
RUN mkdir -p ${i}${r?``:`\nRUN ${n?`pnpm`:`bun`} run build`}
|
|
410
|
+
|
|
411
|
+
FROM ${r?Ur:Hr} AS runner
|
|
412
|
+
${Yr(r)}
|
|
413
|
+
WORKDIR /app
|
|
414
|
+
COPY --from=prod-deps /app/node_modules ./node_modules
|
|
415
|
+
COPY --from=build /app/package.json ./
|
|
416
|
+
COPY --from=build /app/${i} ./${i}
|
|
417
|
+
${r?`COPY --from=build /app/tsconfig.json ./
|
|
418
|
+
COPY --from=build /app/src ./src`:`COPY --from=build /app/dist ./dist`}
|
|
419
|
+
${t.databaseOrm===`prisma`?$r(t,``,r):``}USER ${r?`bun`:`node`}
|
|
420
|
+
EXPOSE ${Wr}
|
|
421
|
+
# Processo direto como PID 1: a app trata o SIGTERM (\`enableShutdownHooks\`)
|
|
422
|
+
# e encerra limpo no redeploy.
|
|
423
|
+
CMD ${Qr(e,t)}
|
|
424
|
+
`}function ii(e,t,n,r,i){let a=t.packageManager===`pnpm`,o=e.dir.slice(0,-1)||`.`,s=t.monorepo?`${e.dir}`:``,c=n.length?`# As \`NEXT_PUBLIC_*\` entram no bundle no build: passe com --build-arg.\n${n.map(([e,t])=>`ARG ${e}=${JSON.stringify(t)}`).join(`
|
|
425
|
+
`)}\nENV ${n.map(([e])=>`${e}=$${e}`).join(` \\
|
|
426
|
+
`)}\n`:``,l=(...e)=>e.filter(Boolean).join(`
|
|
427
|
+
`),u=e.packages.map(e=>`COPY ${e}/package.json ${e}/`),d=e.packages.map(e=>`COPY ${e} ${e}`),f=t.monorepo?a?l(`COPY pnpm-lock.yaml pnpm-workspace.yaml ./`,`RUN pnpm fetch --frozen-lockfile`,`COPY package.json ./`,`COPY ${e.dir}package.json ${e.dir}`,...u,`RUN pnpm install --frozen-lockfile --offline --ignore-scripts --filter "${e.name}..."`,`COPY tsconfig.base.json ./`,...d,`COPY ${o} ${o}`):l(`# O Bun confere o lockfile contra todos os workspaces.`,`COPY package.json bun.lock ./`,...i.map(e=>`COPY ${e}/package.json ${e}/`),`RUN bun install --frozen-lockfile --ignore-scripts --filter ${e.name}`,`COPY tsconfig.base.json ./`,...d,`COPY ${o} ${o}`):l(`COPY package.json ${qr(t)} ./`,`RUN ${a?`pnpm`:`bun`} install --frozen-lockfile --ignore-scripts`,`COPY . .`),p=t.monorepo?a?`RUN pnpm --filter "${e.name}..." -r run build`:`RUN cd ${o} && bun run build`:`RUN ${a?`pnpm`:`bun`} run build`;return`${Jr(e,t,["build dependencias + codigo + `next build` em modo standalone",`runner so o servidor standalone, os estaticos e o public`])}
|
|
428
|
+
${a?Xr(t):Zr()}
|
|
429
|
+
FROM base AS build
|
|
430
|
+
ENV NEXT_TELEMETRY_DISABLED=1
|
|
431
|
+
${f}
|
|
432
|
+
${c}${p}
|
|
433
|
+
|
|
434
|
+
FROM ${Hr} AS runner
|
|
435
|
+
ENV NODE_ENV=production \\
|
|
436
|
+
NEXT_TELEMETRY_DISABLED=1 \\
|
|
437
|
+
PORT=${Gr} \\
|
|
438
|
+
HOSTNAME=0.0.0.0
|
|
439
|
+
WORKDIR /app
|
|
440
|
+
# O standalone ja traz o node_modules minimo que o servidor importa; os
|
|
441
|
+
# estaticos e o public nao entram nele e vao ao lado.
|
|
442
|
+
COPY --from=build /app/${e.dir}.next/standalone ./
|
|
443
|
+
COPY --from=build /app/${e.dir}.next/static ./${s}.next/static
|
|
444
|
+
${r?`COPY --from=build /app/${e.dir}public ./${s}public\n`:``}USER node
|
|
445
|
+
EXPOSE ${Gr}
|
|
446
|
+
CMD ${Qr(e,t)}
|
|
447
|
+
`}function ai(e){return`import path from 'node:path';
|
|
448
|
+
import { drizzle } from 'drizzle-orm/postgres-js';
|
|
449
|
+
import { migrate } from 'drizzle-orm/postgres-js/migrator';
|
|
450
|
+
import postgres from 'postgres';
|
|
451
|
+
import { env } from '${e}';
|
|
452
|
+
|
|
453
|
+
/**
|
|
454
|
+
* Aplica as migrations pendentes e sai.
|
|
455
|
+
*
|
|
456
|
+
* @remarks
|
|
457
|
+
* Roda no pre-deploy da imagem de producao, onde o \`drizzle-kit\`
|
|
458
|
+
* (dependencia de desenvolvimento) nao existe: o migrator do \`drizzle-orm\`
|
|
459
|
+
* le a mesma pasta que o \`drizzle-kit generate\` escreve.
|
|
460
|
+
*/
|
|
461
|
+
async function main(): Promise<void> {
|
|
462
|
+
const connection = postgres(env.DATABASE_URL, { max: 1 });
|
|
463
|
+
|
|
464
|
+
try {
|
|
465
|
+
await migrate(drizzle(connection), {
|
|
466
|
+
migrationsFolder: path.join(__dirname, '../../../drizzle'),
|
|
467
|
+
});
|
|
468
|
+
} finally {
|
|
469
|
+
await connection.end();
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
void main().catch((error: unknown) => {
|
|
474
|
+
console.error(error);
|
|
475
|
+
process.exitCode = 1;
|
|
476
|
+
});
|
|
477
|
+
`}function W(e,t){let n=e.get(t)?.content;return n?JSON.parse(n):void 0}function oi(e,t){if(!t.features.dockerfile)return e;let n=new Map(e.map(e=>[e.path,{...e}])),r=W(n,`package.json`),i=n.has(`apps/api/package.json`),a=/* @__PURE__ */ new Map;for(let e of n.keys()){let t=/^(packages\/[^/]+)\/package\.json$/.exec(e);t?.[1]&&a.set(W(n,e)?.name,t[1])}let o={packageManager:t.packageManager,runtime:t.runtime,databaseOrm:t.databaseOrm,packageManagerVersion:r?.packageManager??``,prismaRange:r?.devDependencies?.prisma??W(n,`packages/database/package.json`)?.devDependencies?.prisma??`^6`,monorepo:i},s=e=>Object.entries(e.dependencies??{}).filter(([,e])=>e.startsWith(`workspace:`)).map(([e])=>a.get(e)).filter(e=>!!e),l=(e,t=[])=>{for(let r of e)t.includes(r)||(l(s(W(n,`${r}/package.json`)??{}),t),t.includes(r)||t.push(r));return t},u=(e,t)=>{let r=W(n,`${t}package.json`)??{},a=l(s(r)),o=i?a.find(e=>e===`packages/database`):void 0,c=o?W(n,`${o}/package.json`)?.name:void 0;return{kind:e,dir:t,name:r.name,packages:a,databaseDir:o,databaseName:c}},d=[...n.keys()].filter(e=>/^(apps\/[^/]+|apps\/workers\/[^/]+|packages\/[^/]+)\/package\.json$/.test(e)).map(e=>c.posix.dirname(e)).sort(),f=e=>i?o.packageManager===`pnpm`?ti(e,o):ni(e,o,d):ri(e,o),p=i?`apps/api/`:``,m=[];n.has(`${p}Dockerfile`)&&n.has(`${p}nest-cli.json`)&&m.push(u(`api`,p));for(let e of d)e.startsWith(`apps/workers/`)&&m.push(u(`worker`,`${e}/`));let h=i?`apps/web/`:``,g=n.has(`${h}package.json`)&&W(n,`${h}package.json`)?.dependencies?.next&&t.hosting?.web!==`cloudflare`&&(n.has(`${h}Dockerfile`)||i);for(let e of m)n.set(`${e.dir}Dockerfile`,{path:`${e.dir}Dockerfile`,content:f(e)});if(g){let e=u(`web`,h),t=(n.get(`${h}.env.example`)?.content??``).split(`
|
|
478
|
+
`).map(e=>/^(NEXT_PUBLIC_[A-Z0-9_]+)="?([^"]*)"?$/.exec(e)).filter(e=>e!==null).map(e=>[e[1]??``,e[2]??``]),r=[...n.keys()].some(e=>e.startsWith(`${h}public/`));n.set(`${h}Dockerfile`,{path:`${h}Dockerfile`,content:ii(e,o,t,r,d)});for(let e of[`${h}src/types/config/next.config.mjs`,`${h}next.config.mjs`]){let t=n.get(e);if(!t?.content?.includes(`const nextConfig = {`))continue;let r=c.posix.relative(c.posix.dirname(e),`.`);t.content=t.content.replace(`const nextConfig = {`,`const nextConfig = {\n\t/* Imagem Docker enxuta: so o servidor e o que ele importa. */\n\toutput: 'standalone',${i?`\n\t/* Raiz do monorepo, para o trace achar os packages do workspace. */\n\toutputFileTracingRoot: fileURLToPath(new URL('${r}/', import.meta.url)),`:``}`),i&&(t.content=`import { fileURLToPath } from 'node:url';\n\n${t.content}`)}}let _=m.find(e=>e.kind===`api`);if(_&&o.databaseOrm!==`prisma`){let e=i?`${_.databaseDir}/src/shared/migrations/migrate.ts`:`src/shared/database/migrate.ts`;(!i||_.databaseDir)&&n.set(e,{path:e,content:ai(`../../env`)})}let v=o.runtime===`bun`?`bun`:`node`,y=e=>{if(o.databaseOrm===`prisma`){let t=o.runtime===`bun`?`bunx`:`npx --yes`,n=i?o.packageManager===`pnpm`?`node_modules/${e.databaseName}/prisma/schema.prisma`:`../../packages/database/prisma/schema.prisma`:`prisma/schema.prisma`;return`${t} prisma@${o.prismaRange} migrate deploy --schema ${n}`}return i?o.packageManager===`pnpm`?`${v} node_modules/${e.databaseName}/dist/shared/migrations/migrate.js`:`${v} ../../packages/database/dist/shared/migrations/migrate.js`:o.runtime===`bun`?`bun src/shared/database/migrate.ts`:`node dist/shared/database/migrate.js`},b=e=>[`.dockerignore`,e.dir?`${e.dir}**`:`src/**`,...e.packages.map(e=>`${e}/**`),`package.json`,qr(o),i?`tsconfig.base.json`:`tsconfig.json`],x=n.get(`${p}railway.json`);if(_&&x?.content){let e=JSON.parse(x.content);e.build.watchPatterns=b(_),e.deploy?.preDeployCommand&&(e.deploy.preDeployCommand=y(_)),x.content=B(e);for(let e of m)e.kind===`worker`&&n.set(`${e.dir}railway.json`,{path:`${e.dir}railway.json`,content:B({$schema:`https://railway.com/railway.schema.json`,build:{builder:`DOCKERFILE`,dockerfilePath:`${e.dir}Dockerfile`,watchPatterns:b(e)},deploy:{restartPolicyType:`ON_FAILURE`,restartPolicyMaxRetries:10}})})}return[...n.values()]}const si={MESSAGING_API_KEY:{en:`Messaging credential required to send transactional email.`,pt:`Credencial da plataforma Messaging para enviar e-mails transacionais.`},MESSAGING_FROM:{en:`Verified sender address required for outgoing email.`,pt:`Remetente verificado dos e-mails enviados.`},NODE_ENV:{en:`Runtime mode; outside production, optional credentials may stay empty.`,pt:`Modo de execução; fora de produção, credenciais opcionais podem ficar vazias.`},PORT:{en:`HTTP port used to listen for API requests.`,pt:`Porta HTTP em que a API escuta.`},API_URL:{en:`Public API origin used for documentation and generated links.`,pt:`Origem pública da API, usada na documentação e em links gerados.`},API_DOCS_ENABLED:{en:`Enables API documentation when it should be publicly available.`,pt:`Liga a documentação da API quando ela pode ficar pública.`},DATABASE_URL:{en:`PostgreSQL connection string required to access application data.`,pt:`Connection string do PostgreSQL.`},REDIS_URL:{en:`Redis connection string required for cache and traditional queues.`,pt:`Connection string do Redis, para cache e filas.`},REDIS_PASSWORD:{en:`Local Redis password required to authenticate development clients.`,pt:`Senha do Redis local de desenvolvimento.`},BETTER_AUTH_SECRET:{en:`Signing secret required to protect authentication sessions.`,pt:`Segredo que assina as sessões de autenticação.`},BETTER_AUTH_URL:{en:`Authentication origin required for redirects and session endpoints.`,pt:`Origem da autenticação, usada em redirects e nas rotas de sessão.`},ROCKFELLER_CLIENT_ID:{en:`Rockfeller SSO client identifier required for Conta Rockfeller login.`,pt:`Client ID do Rockfeller SSO para o login pela Conta Rockfeller.`},ROCKFELLER_CLIENT_SECRET:{en:`Rockfeller SSO client secret required for Conta Rockfeller login.`,pt:`Client secret do Rockfeller SSO para o login pela Conta Rockfeller.`},CLIENT_ORIGIN:{en:`Website origin allowed to send authenticated API requests.`,pt:`Origem do website autorizada a chamar a API com sessão.`},NEXT_PUBLIC_API_URL:{en:`API origin required for browser requests.`,pt:`Origem da API chamada pelo navegador.`},NEXT_PUBLIC_AUTH_URL:{en:`Authentication origin required for browser login and sessions.`,pt:`Origem da autenticação usada pelo navegador no login e na sessão.`},NEXT_PUBLIC_APP_NAME:{en:`Application name used in the website interface.`,pt:`Nome da aplicação exibido no website.`},OTEL_SERVICE_NAME:{en:`Service name required to identify telemetry from this application.`,pt:`Nome do serviço que identifica a telemetria desta aplicação.`},OTEL_SERVICE_VERSION:{en:`Service version used to correlate telemetry with releases.`,pt:`Versão do serviço, para ligar a telemetria a uma release.`},LOG_LEVEL:{en:`Minimum log severity used to control diagnostic output.`,pt:`Severidade mínima dos logs.`},TELEMETRY_ENABLED:{en:`Turns telemetry export on; off in local development, on in production.`,pt:`Liga a exportação de telemetria; desligada no dev local, ligada em produção.`},TELEMETRY_HTTP_SUCCESS_LOGS_ENABLED:{en:`Enables successful request logs when detailed HTTP diagnostics are needed.`,pt:`Liga o log de requisições bem-sucedidas, para diagnóstico detalhado.`},TELEMETRY_HTTP_SLOW_REQUEST_MS:{en:`Request duration threshold used to identify slow HTTP calls.`,pt:`Duração a partir da qual uma requisição HTTP conta como lenta.`},POSTHOG_API_KEY:{en:`PostHog key used to send telemetry; required in production.`,pt:`Chave do PostHog para a telemetria; obrigatória em produção.`},POSTHOG_HOST:{en:`PostHog ingestion origin used to route telemetry to the correct region.`,pt:`Origem de ingestão do PostHog, conforme a região.`},BETTERSTACK_OTLP_ENDPOINT:{en:`Better Stack collector endpoint; required in production.`,pt:`Endpoint do coletor Better Stack; obrigatório em produção.`},BETTERSTACK_ERRORS_DSN:{en:`Better Stack DSN used to report errors; required in production.`,pt:`DSN do Better Stack para reportar erros; obrigatório em produção.`},TUNNEL_TOKEN:{en:`Tunnel credential required to connect Railway to the private Cloudflare network.`,pt:`Credencial do Tunnel que liga a Railway à rede privada do Cloudflare.`},QUEUE_REDIS_URL:{en:`Redis connection string required to consume this worker’s queue.`,pt:`Connection string do Redis de onde o worker consome a fila.`},QUEUE_NAME:{en:`Queue identifier required to route jobs to this worker.`,pt:`Nome da fila consumida por este worker.`},QUEUE_PREFIX:{en:`Redis key prefix required to isolate this project’s queues.`,pt:`Prefixo das chaves Redis que isola as filas deste projeto.`},WORKER_CONCURRENCY:{en:`Maximum parallel jobs used to control worker load.`,pt:`Máximo de jobs em paralelo no worker.`},WEBHOOK_SECRETS_KEY:{en:`Base64 AES-256 key (openssl rand -base64 32) that encrypts webhook secrets; the same in the API and the webhooks worker.`,pt:`Chave AES-256 em base64 (openssl rand -base64 32) que cifra os segredos dos webhooks; a mesma na API e no worker webhooks.`},WEBHOOKS_DISPATCH_INTERVAL_MS:{en:`Pause between outbox reads when no event is waiting.`,pt:`Pausa entre leituras do outbox quando não há evento esperando.`},WEBHOOKS_DISPATCH_BATCH_SIZE:{en:`Maximum outbox events moved to the delivery queue per read.`,pt:`Máximo de eventos do outbox levados para a fila por leitura.`},WEBHOOKS_TIMEOUT_MS:{en:`Time limit for each webhook delivery request.`,pt:`Tempo máximo de cada requisição de entrega de webhook.`}};function ci(e,t=`en`){let n=/^(GOOGLE|GITHUB|DISCORD)_(CLIENT_ID|CLIENT_SECRET)$/.exec(e);if(n){let e=n[2]===`CLIENT_ID`;return t===`pt`?`${e?`Client ID`:`Client secret`} OAuth do provider ${n[1]}.`:`${n[1]} OAuth ${e?`client identifier`:`client secret`} required for this login provider.`}let r=si[e];if(!r)throw Error(`Missing environment documentation for ${e}.`);return r[t]}function li(e){return ci(e,`pt`)}function ui(e){return e.map(e=>{if(!/(?:^|\/)(?:\.env|\.dev\.vars)(?:\.|$)/.test(e.path)||e.content===void 0)return e;let t=e.content.replace(/^(?:export\s+)?([A-Z][A-Z0-9_]*)=.*$/gm,(e,t)=>`# ${ci(t)}\n${e}`);return t=`${t.replace(/(^(?:export\s+)?[A-Z][A-Z0-9_]*=[^\r\n]*)(?:\r?\n(?:[\t ]*\r?\n)*)?/gm,`$1
|
|
479
|
+
|
|
480
|
+
`).trimEnd()}\n`,{...e,content:t}})}function di(e,t={}){let n=Object.entries(t).filter(([,e])=>e);return n.length===0?e:e.map(e=>{if(!/(?:^|\/)(?:\.env|\.dev\.vars)$/.test(e.path)||e.content===void 0)return e;let t=e.content;for(let[e,r]of n)t=t.replace(RegExp(`^((?:export\\s+)?${e}=).*$`,`m`),(e,t)=>`${t}${JSON.stringify(r)}`);return{...e,content:t}})}function fi(e){let{context:t}=e,n=t.packageManager,r=e.apiDir?e.apiDir.replace(/\/$/,``):`.`,i=e.webDir?e.webDir.replace(/\/$/,``):`.`,a=[`## Cloudflare`,``,"API and website deploy separately. `rock new` creates no Cloudflare resources and publishes nothing; every step below is manual.",``];return e.cloudflareApi&&a.push(`### NestJS API on Workers`,``,"1. At the repository root, run `docker compose up -d postgres`.",`2. In \`${r}\`, copy \`.dev.vars.example\` to \`.dev.vars\` and fill in the auth variables when auth is enabled.`,`3. Migrations use \`DATABASE_URL\` from the database package \`.env\` and the local PostgreSQL. ${t.databaseOrm===`prisma`?'With Better Auth, run `auth:generate` in the API package, review the schema and keep `engineType = "client"` in Prisma, then run':`Run`} \`${n} run db:migrate\` at the root.`,`4. Run \`${n} run dev\` at the root${e.template===`monolith`?`; \`${n} run dev:api\` starts only the API`:``}.`,"5. Check `http://localhost:3001/v1/health` and `http://localhost:3001/v1/docs`.",``,"The Nest bootstrap keeps decorators, validation, CORS and auth. Each invocation creates and closes its own providers and PostgreSQL clients: never move connections to global scope. HTTP goes through the official `httpServerHandler` adapter from `cloudflare:node`. The NestJS/SWC build keeps decorator metadata before the Wrangler bundle.",``,`#### Private PostgreSQL on Railway`,``,`The database stays on Railway. Workers VPC is in beta. Configure these resources by hand:`,``,"1. Create a Cloudflare Tunnel and copy its token. On Railway, create a service in the same project and environment as PostgreSQL, using `infra/cloudflared/Dockerfile` and `infra/cloudflared/railway.json`. Set `TUNNEL_TOKEN` as a secret variable on Railway.",`2. Create a TCP VPC Service on port 5432, PostgreSQL protocol, with the Tunnel ID and the private database hostname. cloudflared must be able to resolve and reach that hostname.`,`3. Create a Hyperdrive config for that VPC Service with the database name, user and password. Keep TLS with certificate and hostname validation; never disable TLS to work around an incompatibility.`,`4. Replace the all-zero \`HYPERDRIVE\` binding ID in \`${r}/wrangler.jsonc\` with the real ID. \`localConnectionString\` keeps pointing to the local database.`,"5. Point `API_URL` and `CLIENT_ORIGIN` to the production domains. Set `BETTER_AUTH_URL`, `BETTER_AUTH_SECRET` and every other secret with `wrangler secret put`; never commit their values.",`6. Production migrations run separately, before the deploy, from a machine or service allowed to reach Railway. Hyperdrive does not run migrations; never point a local migration at production by mistake. ${t.databaseOrm===`prisma`?"Use `prisma migrate deploy`.":"Use `drizzle-kit migrate` in the database package."}`,`7. In \`${r}\`, run \`${n} run deploy\`${e.template===`monolith`?` after building the shared packages`:``}. Validate health, auth and database access in the real environment.`,``,`#### Cache and queues`,``,t.hosting?.kv?"Create a KV namespace and replace the all-zero `CACHE` ID in `wrangler.jsonc`. KV is eventually consistent and its minimum TTL is 60 seconds: never use it as a lock or a session store.":"KV is disabled. `CacheService` returns a miss and writes nothing without the `CACHE` binding; health does not require a missing cache.",``,t.workers.length?`Create the queues ${t.workers.map(e=>`\`${t.projectSlug}-${e.queue}\``).join(`, `)} before publishing. \`QueueService.send\` publishes jobs; implement the handling in \`processJob\`, in \`src/modules/queue/service.ts\`. The consumer acknowledges on success and retries on failure. Delivery is at least once, so handlers must be idempotent.`:`No queues were selected, so there are no BullMQ or Redis processes.`,``,`References: [Hyperdrive + VPC](https://developers.cloudflare.com/hyperdrive/configuration/connect-to-private-database-vpc/) · [Railway private networking](https://docs.railway.com/networking/private-networking/how-it-works) · [Connection lifecycle](https://developers.cloudflare.com/hyperdrive/concepts/connection-lifecycle/)`,``),e.cloudflareWeb&&(t.hosting?.webAdapter===`opennext`?a.push(`### Website on ${e.landing?`Pages (static)`:`Workers (OpenNext)`}`,``,`In \`${i}\`, \`${n} run dev\` starts Next.js; \`${n} run preview\` validates the output on the Cloudflare runtime and \`${n} run deploy\` publishes by hand.`,``,e.landing?"Next.js uses static export. Create the Pages project with the name used by the `deploy` script before publishing. Login, dashboard and server features require moving to Workers.":"OpenNext keeps Next.js as is: `next build` stays the regular build and preview/deploy run the adapter build. Set public URLs in `.env` before building, because `NEXT_PUBLIC_*` is inlined into the bundle. Configure server variables and secrets on Cloudflare.",``,`References: [OpenNext](https://opennext.js.org/cloudflare/get-started) · [Static Next.js on Pages](https://developers.cloudflare.com/pages/framework-guides/nextjs/deploy-a-static-nextjs-site/)`,``):a.push(`### Website on Workers (vinext${e.landing?`, static`:``})`,``,`The website uses [vinext](https://vinext.dev/), the Next.js API on top of Vite, and requires Node.js 22 or newer. vinext is under active development; validate behavior on the Cloudflare runtime before publishing.`,``,`In \`${i}\`, \`${n} run dev\` and \`${n} run build\` still run Next.js. \`${n} run dev:vinext\` and \`${n} run build:vinext\` run the same app through vinext; \`${n} run preview\` validates the output on the Cloudflare runtime and \`${n} run deploy\` publishes by hand. Do not import \`cloudflare:workers\` in code that \`next build\` must compile.`,``,e.landing?"Next.js uses static export: the vinext build writes `dist/client` and the deploy publishes, through `deploy/wrangler.jsonc`, a Worker with static assets only and no server code. Keep that file out of the root: a root `wrangler.jsonc` makes vinext require the Cloudflare plugin. Login, dashboard and server features require a server application.":"The Worker uses `vinext/server/fetch-handler` with assets in `dist/client`. Set public URLs in `.env` before building, because `NEXT_PUBLIC_*` is inlined into the bundle. The build copies `.env` to `dist/server/.dev.vars` for local use only; in production configure secrets with `wrangler secret put` or bindings. Bindings are available through `import { env } from 'cloudflare:workers'`, but that import breaks `next build`: use it only in code that vinext runs.",``,`References: [vinext](https://vinext.dev/) · [Deploying to Cloudflare](https://github.com/cloudflare/vinext/blob/main/docs/deploying/cloudflare.mdx)`,``)),a.join(`
|
|
481
|
+
`)}const G=e=>`\`${e}\``;function pi(e,t){let n=e.get(t)?.content;return n?JSON.parse(n):void 0}function mi(e,t){return pi(e.files,t)?.scripts??{}}function K(e,t){return e.files.has(t)}function hi(e){let{context:t,template:n}=e,r=t.packageManager,i=[];if(n===`monolith`){i.push(["`apps/api/`",`NestJS API.`],["`apps/web/`",`Next.js website.`]),t.workers.length&&!e.cloudflareApi&&i.push(["`apps/workers/<name>/`",`BullMQ consumers, one app per queue, no HTTP.`]);for(let[t,n]of[[`packages/database`,"Tables, migrations and `DatabaseService`."],[`packages/cache`,"`CacheService`."],[`packages/jobs`,`Queue names, job contracts and default job options.`],[`packages/queue`,`Shared BullMQ connections.`],[`packages/observability`,"Telemetry adapters, process bootstrap and the job lifecycle (`runObservedJob`, `observeWorker`) shared by the API and the workers."]])K(e,`${t}/package.json`)&&i.push([`\`${t}/\``,n])}else i.push(["`src/`",n===`api`?`NestJS API.`:`Next.js website.`]);K(e,`infra/cloudflared/Dockerfile`)&&i.push(["`infra/cloudflared/`",`Railway service that connects the private database to Cloudflare.`]);let a=e.apiDir,o=[...e.hasApi?["Nest apps keep the root module in `src/module.ts` and validate environment variables in `src/env.ts`. Add every new variable there and to the matching `.env.example`.",`Feature code lives in \`${a}src/modules/<entity>/\` as \`module.ts\`, \`controller.ts\`, \`service.ts\` and, when needed, \`repository.ts\`. The folder names the entity; the file names the role.`,`Responses and errors come from \`franchising/http\`: return \`ok(data)\`, throw its error functions (\`notFound(Errors.X)\`, \`badRequest(...)\`), and declare app-specific codes with \`defineErrors\` in \`${a}src/shared/http/errors.ts\` (\`CommonErrors\` codes such as \`NotFound\` are reserved). The global \`ErrorFilter\` (\`ErrorsModule\` in \`src/module.ts\`) turns everything into \`{ ok: false, error: { code, message, extra? } }\`, and every 5xx reaches the client as a generic body. Document routes with \`@APIEnvelope\` and \`@APIErrors\` from \`franchising/http/swagger\`. Clients branch on \`error.code\`, never on \`message\`.`,"Routes are versioned in the path (`/v1/...`). Breaking changes go to a new version instead of changing `/v1`."]:[],...K(e,`packages/database/src/tables/index.ts`)||K(e,`src/tables/index.ts`)?["Database tables live in `tables/<category>/<table>.ts`, one table per file. Each category has an `index.ts` that re-exports its tables, `tables/index.ts` re-exports the categories, and every `relations()` lives in `tables/relations.ts`. Generate a migration for every schema change; never edit applied migrations."]:[],...t.features.betterAuth&&e.hasApi?[t.databaseOrm===`prisma`?"The Better Auth models in the Prisma schema are generated by `auth:generate` from the plugins. Do not edit them by hand: change the auth configuration and regenerate.":"Better Auth tables are written by hand in `tables/auth/`, plural (`users`, `sessions`...), because the adapter runs with `usePlural: true`. When enabling a plugin or upgrading Better Auth, add the columns it requires and generate a migration."]:[],...e.queuedMessaging?["The API never talks to the email provider. `MessagingService.sendEmail` only enqueues a `SendEmailJob` (contract in `packages/jobs`); `apps/workers/emails` sends it. Keep provider credentials out of the API."]:[],...t.workers.some(e=>e.kind===`webhooks`)&&!e.cloudflareApi?["Outgoing webhooks follow Standard Webhooks. Publish with `WebhooksService.publish(eventType, payload, ownerId, tx)` inside the business transaction; never call the receiver from the API. Every endpoint query filters by `ownerId`. Secrets stay encrypted with `WEBHOOK_SECRETS_KEY` and are returned only on create and rotate."]:[],...t.workers.length&&!e.cloudflareApi?["Workers must be idempotent: BullMQ delivers at least once and retries failures. Throw `UnrecoverableError` for payloads that will never succeed."]:[],...e.hasWeb?["Website environment variables are validated in `src/env.ts`. `NEXT_PUBLIC_*` values are inlined into the client bundle: never put secrets in them."]:[]];return[`# ${t.projectName} — Agent Guide`,``,`## Purpose`,``,`${n===`monolith`?`Monorepo with a Next.js website, a NestJS API and shared packages`:n===`api`?`NestJS API`:`Next.js website`}, scaffolded by the Rock CLI (\`franchising\`). README.md (Brazilian Portuguese) is the human guide; this file is the contract for agents and contributors.`,``,`## Repository map`,``,`| Path | Responsibility |`,`| --- | --- |`,...i.map(([e,t])=>`| ${e} | ${t} |`),``,`## Conventions`,``,...o.map(e=>`- ${e}`),``,`## Validation`,``,`Run before delivering any change:`,``,"```bash",...[`lint`,`typecheck`,`test`,`build`].filter(t=>mi(e,`package.json`)[t]).map(e=>`${r} run ${e}`),"```",``,`Fix lint and formatting with \`${r} run format\`. Keep the generated code free of lint errors.`,``,`## Security`,``,"- Never commit `.env`, `.dev.vars`, tokens, credentials or production URLs. `.env.example` holds keys only.",`- Never log secrets or personal data (emails, names, documents). Log identifiers and error codes instead.`,...e.hasApi?["- Validate every request body with DTOs and `class-validator`; authorize by ownership, not only by authentication."]:[],``,e.cloudflareApi||e.cloudflareWeb?fi(e):``].join(`
|
|
264
482
|
`).replace(/\n{3,}/g,`
|
|
265
483
|
|
|
266
484
|
`).replace(/\n*$/,`
|
|
267
|
-
`)}function
|
|
268
|
-
`)}function
|
|
269
|
-
`)}function
|
|
270
|
-
`)}function
|
|
271
|
-
`):``}function
|
|
272
|
-
`):``}function
|
|
485
|
+
`)}function gi(e){let{context:t}=e,n=[];if(e.hasWeb){let r=e.cloudflareWeb?t.hosting?.webAdapter===`opennext`?e.landing?`Cloudflare Pages, exportação estática`:`Cloudflare Workers com OpenNext`:e.landing?`Cloudflare Workers, exportação estática via vinext`:`Cloudflare Workers com vinext`:`servidor Node`;n.push(`**Website**: Next.js (App Router) em ${r}${e.landing?``:`, com Tailwind e franchising/ui`}.`)}if(e.hasApi&&(n.push(`**API**: NestJS com Fastify ${e.cloudflareApi?`em Cloudflare Workers`:`em servidor Node`}, rotas versionadas em ${G(`/v1`)} e documentação Scalar em ${G(`/v1/docs`)}.`),n.push(`**Banco**: PostgreSQL com ${t.databaseOrm===`prisma`?`Prisma`:`Drizzle`}${e.cloudflareApi?`, acessado por Hyperdrive em produção`:``}.`),n.push(e.cloudflareApi?`**Cache**: Cloudflare KV ${t.hosting?.kv?`habilitado`:`desativado (o CacheService responde miss)`}.`:`**Cache e filas**: Dragonfly (compatível com Redis) via ioredis.`)),t.features.betterAuth){let e=t.authPlugins.length?`, plugins ${t.authPlugins.join(`, `)}`:``,r=t.authProviders.length?`providers ${t.authProviders.join(`, `)}`:`sem providers próprios`;n.push(`**Autenticação**: Better Auth (${r}${e}).`)}return t.messaging&&n.push(`**E-mail**: plataforma Messaging (${G(`franchising/messaging`)})${e.queuedMessaging?", enviado pelo worker `messaging`":``}.`),t.workers.length&&!e.cloudflareApi&&n.push(`**Workers**: BullMQ, um app por fila (${t.workers.map(e=>G(e.name)).join(`, `)}).`),t.workers.length&&e.cloudflareApi&&n.push(`**Filas**: Cloudflare Queues (${t.workers.map(e=>G(e.queue)).join(`, `)}), consumidas pela própria API.`),t.features.telemetry&&n.push(`**Telemetria**: OpenTelemetry com ${t.telemetryAdapter===`betterstack`?`Better Stack`:`PostHog`}, montada em ${G(K(e,`packages/observability/package.json`)?`packages/observability`:`${e.apiDir}src/shared/observability`)}. Desligada no dev local (${G(`TELEMETRY_ENABLED="false"`)}); em produção liga sozinha e a credencial do destino é obrigatória.`),n.map(e=>`- ${e}`).join(`
|
|
486
|
+
`)}function _i(e){let{context:t}=e;if(e.template!==`monolith`)return``;let n=t.workers.filter(()=>!e.cloudflareApi),r=[`navegador ──► apps/web (Next.js, :3000)`,` └─ fetch ──► apps/api (NestJS, :3001)`,...t.features.betterAuth?[` ├─ Better Auth em /v1/auth`]:[],` ├─ PostgreSQL (packages/database)`,e.cloudflareApi?` └─ Cloudflare KV e Queues`:` └─ Dragonfly (packages/cache${n.length?`, filas BullMQ`:``})`,...n.length?[` │`,` apps/workers (sem HTTP) ◄───┘`,...n.map((e,t)=>` ${t===n.length-1?`└─`:`├─`} ${e.name}: ${e.kind===`messaging`?`envia os e-mails pela plataforma Messaging`:e.kind===`webhooks`?`entrega os webhooks do outbox`:`consome a fila ${e.queue}`}`)]:[]],i=[[`packages/database`,`tabelas, migrations e DatabaseService`],[`packages/cache`,`CacheService`],[`packages/jobs`,`nomes de fila, contratos dos jobs e opções`],[`packages/queue`,`conexões BullMQ compartilhadas`],[`packages/webhooks`,`segredo cifrado, assinatura Standard Webhooks e URL permitida`],[`packages/observability`,`telemetria compartilhada: adapters, bootstrap e ciclo de vida dos jobs`]].filter(([t])=>K(e,`${t}/package.json`)),a=[[`apps/`,``],[` api/`,`API NestJS`],[` web/`,`website Next.js`],...n.length?[[` workers/`,``]]:[],...n.map(e=>[` ${e.name}/`,e.kind===`messaging`?`envio dos e-mails`:e.kind===`webhooks`?`entrega dos webhooks`:`consumidor da fila ${e.queue}`]),[`packages/`,``],...i.map(([e,t])=>[` ${e.replace(`packages/`,``)}/`,t])],o=Math.max(...a.map(([e])=>e.length))+2,s=a.map(([e,t])=>t?`${e.padEnd(o)}${t}`:e);return[`## Arquitetura`,``,"```",...r,"```",``,"```",...s,"```",``,`API e website têm deploys separados. Os packages são internos ao monorepo e só existem para os apps compartilharem código.`,``].join(`
|
|
487
|
+
`)}function vi(e){if(!e.hasApi)return``;let t=e.apiDir,n=e.template===`monolith`?`packages/database/src/tables`:`${t}src/tables`;return[`### Organização da API`,``,`| Caminho | Conteúdo |`,`| --- | --- |`,...[[`${t}src/main.ts`,`bootstrap do Nest (CORS, validação, versionamento e docs)`],[`${t}src/module.ts`,`módulo raiz`],[`${t}src/env.ts`,`validação das variáveis de ambiente (envalid)`],[`${t}src/shared/http/errors.ts`,"erros do app com `defineErrors` do `franchising/http` (respostas com `ok()`, filtro global `ErrorsModule`)"],[`${t}src/modules/<entidade>/`,"`module.ts`, `controller.ts`, `service.ts`"],...e.context.features.betterAuth?[[`${t}src/auth.ts`,`instância do Better Auth`]]:[],...K(e,`${n}/index.ts`)?[[`${n}/`,`uma tabela Drizzle por arquivo`]]:[]].map(([e,t])=>`| ${G(e)} | ${t} |`),``].join(`
|
|
488
|
+
`)}function yi(e){let{features:t,workflows:n}=e.context,r=[...t.ultracite?[`Ultracite (oxlint + oxfmt) para lint e formatação`]:[],...t.lefthook?[`Lefthook corrige e linta os arquivos staged no commit, valida a mensagem (com commitlint) e roda lint, typecheck e testes em paralelo no push`]:[],...t.commitlint?[`commitlint exige Conventional Commits`]:[],...n.includes(`quality`)?["GitHub Actions roda lint, typecheck, testes e build em jobs paralelos em cada PR; o check agregado `Quality` é o que a branch protection deve exigir"]:[],"O template de PR (`.github/PULL_REQUEST_TEMPLATE.md`) segue o padrão do `github-config`",...n.includes(`codeql`)?[`CodeQL procura vulnerabilidades`]:[],...n.includes(`dependencyReview`)?[`Dependency Review avalia dependências novas nos PRs`]:[]];return r.length?[`## Qualidade`,``,...r.map(e=>`- ${e}.`),``].join(`
|
|
489
|
+
`):``}function bi(e){let{context:t}=e,n=[],r=[...e.files.keys()].find(e=>e.endsWith(`railway.json`)&&!e.startsWith(`infra/`)&&!e.startsWith(`apps/workers/`)),i=K(e,`${e.apiDir}Dockerfile`)?[`- **Imagens**: os Dockerfiles buildam a partir da raiz (${G(`docker build -f ${e.apiDir}Dockerfile .`)}), em estágios que separam dependências de produção e build, levam só os packages do workspace que cada app usa e rodam o código compilado como usuário sem privilégio. As migrations do pre-deploy não dependem de ferramenta de desenvolvimento.`]:[];r?n.push(`- **API na Railway**: usa ${G(r)} e o Dockerfile da API. As migrations rodam no pre-deploy e o healthcheck é ${G(`/v1/health`)}. Configure as variáveis do ${G(`${e.apiDir}.env.example`)} no serviço.`):e.hasApi&&!e.cloudflareApi&&K(e,`${e.apiDir}Dockerfile`)&&n.push(`- **API**: ${G(`${e.apiDir}Dockerfile`)} gera a imagem. Rode as migrations antes de subir uma versão nova e use ${G(`/v1/health`)} como healthcheck.`);let a=[...e.files.keys()].find(e=>e.endsWith(`vercel.json`));return a?n.push(`- **Website na Vercel**: usa ${G(a)}. Configure as variáveis ${G(`NEXT_PUBLIC_*`)} antes do build, pois elas vão para o bundle.`):e.hasWeb&&!e.cloudflareWeb&&K(e,`${e.webDir}Dockerfile`)&&n.push(`- **Website**: ${G(`${e.webDir}Dockerfile`)} gera a imagem do Next.js em modo ${G(`standalone`)}. As ${G(`NEXT_PUBLIC_*`)} entram como ${G(`--build-arg`)}.`),(e.cloudflareApi||e.cloudflareWeb)&&n.push(`- **Cloudflare**: ${[e.cloudflareApi?`a API`:``,e.cloudflareWeb?`o website`:``].filter(Boolean).join(` e `)} publica${e.cloudflareApi&&e.cloudflareWeb?`m`:``} com Wrangler (${G(e.run(e.template===`monolith`?e.cloudflareApi?`deploy:api`:`deploy:web`:`deploy`))}). O passo a passo, com Hyperdrive, Tunnel e segredos, está na seção Cloudflare do [AGENTS.md](AGENTS.md). O scaffold não cria recursos nem publica nada.`),t.workers.length&&!e.cloudflareApi&&n.push(`- **Workers**: cada ${G(`apps/workers/<nome>`)} é um serviço próprio, sem porta HTTP, com o mesmo Redis da API${K(e,`apps/workers/${t.workers[0]?.name}/Dockerfile`)?`, o próprio Dockerfile${r?` e o próprio railway.json`:``}`:``}.`),n.push(...i),n.length?[`## Deploy`,``,...n,``,"Nunca versione `.env`, tokens ou credenciais de produção.",``].join(`
|
|
490
|
+
`):``}function xi(e){let t=[...e.files.values()].filter(e=>/(?:^|\/)(?:\.env|\.dev\.vars)\.example$/.test(e.path)&&!e.path.startsWith(`infra/`)&&e.content).sort((e,t)=>e.path.localeCompare(t.path));if(t.length===0)return``;let n=t.map(e=>{let t=[...(e.content??``).matchAll(/^([A-Z][A-Z0-9_]*)=/gm)].map(e=>e[1]),n=e.path.replace(/\.example$/,``);return[`### ${G(n)}`,``,`| Variável | Para que serve |`,`| --- | --- |`,...t.map(e=>`| ${G(e)} | ${li(e)} |`)].join(`
|
|
273
491
|
`)});return[`## Variáveis de ambiente`,``,`Cada ${G(`.env`)} já vem com valores de desenvolvimento local e fica fora do Git. O ${G(`.env.example`)} ao lado é o modelo versionado: só chaves, sem segredos. Ao criar uma variável, declare-a no ${G(`src/env.ts`)} do app e no ${G(`.env.example`)}; ${G(`rock env check`)} compara os dois arquivos.`,``,...n.flatMap(e=>[e,``])].join(`
|
|
274
|
-
`)}function
|
|
275
|
-
`)}function
|
|
276
|
-
`)
|
|
277
|
-
`)}function
|
|
278
|
-
`)}function
|
|
279
|
-
`)}function
|
|
492
|
+
`)}function Si(e){let{context:t}=e;if(!t.features.betterAuth)return``;let n=e.template===`monolith`?`packages/database/src/tables/auth/`:`src/tables/auth/`,r=e.template===`monolith`?e.runIn(`api`,`auth:generate`):e.run(`auth:generate`),i=[`## Autenticação`,``,e.hasApi?`O Better Auth roda na API (${G(`${e.apiDir}src/auth.ts`)}), com as rotas em ${G(`/v1/auth/*`)}.${t.implementAuthModule?` O módulo ${G(`@thallesp/nestjs-better-auth`)} protege todas as rotas por padrão; use ${G(`@AllowAnonymous()`)} nas públicas.`:``}`:`O website consome um Better Auth existente: configure ${G(`NEXT_PUBLIC_AUTH_URL`)} com a origem da API.`,``];e.hasApi&&i.push(t.databaseOrm===`prisma`?`As tabelas do Better Auth são geradas: ${G(r)} lê os plugins configurados e grava ${G(`prisma/schema.prisma`)}. Rode de novo sempre que mudar plugins ou providers e gere a migration em seguida.`:`As tabelas do Better Auth são escritas à mão em ${G(n)}, uma por arquivo e no plural (${G(`users`)}, ${G(`sessions`)}...), com o adapter em ${G(`usePlural: true`)}. Ao ligar um plugin ou subir a versão do Better Auth, confira as colunas que ele exige na documentação, ajuste a tabela e gere a migration.`,``),t.authPlugins.includes(`rockfellerSso`)&&i.push(`O login pela Conta Rockfeller usa ${G(`ROCKFELLER_CLIENT_ID`)} e ${G(`ROCKFELLER_CLIENT_SECRET`)} no ${G(`${e.apiDir}.env`)}. Peça o cliente OIDC ao time do Accounts, com a URL de retorno ${G(`<BETTER_AUTH_URL>/v1/auth/oauth2/callback/rockfeller`)}.`,``);let a=t.authProviders.filter(e=>e!==`emailAndPassword`);return a.length&&i.push(`Providers sociais (${a.join(`, `)}) precisam de ${G(`<PROVIDER>_CLIENT_ID`)} e ${G(`<PROVIDER>_CLIENT_SECRET`)} no ${G(`${e.apiDir}.env`)}.`,``),i.join(`
|
|
493
|
+
`)}function Ci(e){return!e.context.workers.some(e=>e.kind===`webhooks`)||e.cloudflareApi?``:[`## Webhooks`,``,`Entrega de webhooks no padrão [Standard Webhooks](https://www.standardwebhooks.com) (cabeçalhos ${G(`webhook-id`)}, ${G(`webhook-timestamp`)} e ${G(`webhook-signature`)}, segredos ${G(`whsec_...`)}).`,``,`- **Publicar**: ${G(`WebhooksService.publish(eventType, payload, ownerId, tx)`)} grava o evento em ${G(`webhook_outbox`)}. Passe a transação da mudança de negócio: o evento existe se e somente se a mudança foi gravada.`,`- **Entregar**: o worker ${G(`apps/workers/webhooks`)} lê o outbox com ${G(`FOR UPDATE SKIP LOCKED`)}, enfileira um job por endpoint inscrito no evento, assina e faz o POST. 5xx, 408, 429 e erro de rede retentam com backoff; os outros 4xx desistem. Cada tentativa fica em ${G(`webhook_deliveries`)}.`,`- **Cadastrar**: ${e.context.implementAuthModule&&e.context.features.betterAuth?`${G(`/v1/webhooks/endpoints`)} (listar, criar, ${G(`:id/rotate-secret`)} e ${G(`DELETE :id`)}, que desativa). Cada usuário só vê os próprios endpoints.`:`pelo ${G(`WebhooksService`)} (create, list, rotateSecret, disable); as rotas exigem o módulo de auth NestJS, então exponha com a autorização que o produto pedir.`} O segredo aparece só na criação e na rotação.`,`- **Segredos**: ficam cifrados (AES-256-GCM) com ${G(`WEBHOOK_SECRETS_KEY`)}, a mesma na API e no worker. Gere com ${G(`openssl rand -base64 32`)}; o ${G(`.env`)} de dev já vem com uma chave.`,`- **URL**: em produção só ${G(`https`)} sem host privado (proteção contra SSRF). Um nome que resolve para IP interno passa pela checagem: restrinja a saída de rede do worker.`,``].join(`
|
|
494
|
+
`)}function wi(e){return e.context.messaging?[`## E-mail`,``,e.queuedMessaging?`A API não fala com o provedor de e-mail: ${G(`MessagingService.sendEmail`)} publica um job na fila ${G(`emails`)} e responde. O worker ${G(`apps/workers/emails`)} consome a fila e envia pela plataforma Messaging, com retentativa. O contrato do job (${G(`SendEmailJob`)}) fica em ${G(`packages/jobs`)}, então API e worker não divergem.\n\nConfigure ${G(`MESSAGING_API_KEY`)} e ${G(`MESSAGING_FROM`)} em ${G(`apps/workers/emails/.env`)}. Sem a chave, em desenvolvimento o worker escreve o e-mail no console (útil para testar links de login); em produção o job falha.`:`O ${G(`MessagingService`)} da API envia pela plataforma Messaging. Configure ${G(`MESSAGING_API_KEY`)} e ${G(`MESSAGING_FROM`)}; sem a chave, o envio falha e vira log, sem derrubar a requisição.`,``].join(`
|
|
495
|
+
`):``}function Ti(e){return e.kind===`messaging`?`envia os e-mails enfileirados pela API.`:e.kind===`webhooks`?`entrega os webhooks de saída (seção Webhooks).`:`consome a fila ${G(e.queue)}. A lógica do job fica em ${G(`apps/workers/${e.name}/src/modules/queue/processor.ts`)}.`}function Ei(e){let t=e.context.workers;return!t.length||e.cloudflareApi?``:[`## Workers`,``,`Cada fila tem um app em ${G(`apps/workers/<nome>`)}, sem HTTP, para escalar e publicar separado; uma fila travada não segura as outras. Os nomes das filas ficam em ${G(`packages/jobs`)}, compartilhados entre quem publica e quem consome.`,``,...t.map(e=>`- ${G(e.name)}: ${Ti(e)}`),``,`${G(e.run(`dev`))} sobe os workers junto com os apps. Para um só: ${G(e.runIn(`@${e.context.projectSlug}/worker-${t[0]?.name}`,`dev`))}.`,``].join(`
|
|
496
|
+
`)}function Di(e,t){let n=e.context.databaseOrm===`prisma`;return{dev:e.template===`monolith`?`Builda os packages compartilhados e sobe os apps${e.context.workers.length&&!e.cloudflareApi?` e workers`:``} em watch.`:`Sobe o projeto em modo desenvolvimento.`,"dev:web":`Sobe só o website.`,"dev:api":`Builda os packages compartilhados e sobe só a API.`,"start:api":`Builda os packages compartilhados e sobe a API em produção (o que o Dockerfile roda).`,"dev:vinext":`Sobe o website pelo vinext, como no Cloudflare.`,build:e.cloudflareApi?`Build e bundle local da API, sem publicar.`:`Build de produção.`,"build:vinext":`Build do website pelo vinext.`,start:`Sobe o build de produção.`,test:`Roda os testes.`,typecheck:`Checa os tipos TypeScript.`,lint:`Checa lint e formatação.`,format:`Corrige lint e formatação.`,check:`Lint, typecheck e testes, como no CI.`,"db:generate":n?`Gera o client do Prisma.`:`Gera a migration a partir das tabelas.`,"db:migrate":`Aplica as migrations no banco local.`,"db:studio":`Abre o studio do banco.`,"auth:generate":`Regenera as tabelas do Better Auth a partir dos plugins configurados.`,preview:`Valida o build no runtime do Cloudflare, localmente.`,deploy:`Publica no Cloudflare.`,"deploy:api":`Publica a API no Cloudflare.`,"deploy:web":`Publica o website no Cloudflare.`}[t]}function Oi(e){let t=[];for(let n of Object.keys(mi(e,`package.json`))){let r=Di(e,n);r&&t.push(`| ${G(e.run(n))} | ${r} |`)}if(e.template===`monolith`){mi(e,`apps/api/package.json`)[`auth:generate`]&&t.push(`| ${G(e.runIn(`api`,`auth:generate`))} | ${Di(e,`auth:generate`)} |`);for(let[n,r]of[[`apps/api`,`api`],[`apps/web`,`web`]]){let i=mi(e,`${n}/package.json`);for(let n of[`preview`,`dev:vinext`])i[n]&&t.push(`| ${G(e.runIn(r,n))} | ${Di(e,n)} |`)}}return[`| Comando | O que faz |`,`| --- | --- |`,...t].join(`
|
|
497
|
+
`)}function ki(e){let{context:t}=e,n=t.packageManager,r=[[`${n} install`,``]];K(e,`docker-compose.yml`)&&r.push(e.cloudflareApi?[`docker compose up -d postgres`,`PostgreSQL local`]:[`docker compose up -d`,`PostgreSQL (:7000) e Dragonfly (:6379)`]),e.cloudflareApi&&r.push([`cp ${e.apiDir}.dev.vars.example ${e.apiDir}.dev.vars`,`variáveis locais do Wrangler`]),e.hasApi&&(t.features.betterAuth&&t.databaseOrm===`prisma`&&r.push([e.template===`monolith`?e.runIn(`api`,`auth:generate`):e.run(`auth:generate`),`tabelas do Better Auth`]),t.databaseOrm!==`prisma`&&r.push([e.run(`db:generate`),`migration inicial`]),r.push([e.run(`db:migrate`),`aplica no banco local`])),r.push([e.run(`dev`),``]);let i=Math.max(...r.map(([e])=>e.length))+2,a=r.map(([e,t])=>t?`${e.padEnd(i)}# ${t}`:e),o=[...e.hasWeb?[`website em http://localhost:3000`]:[],...e.hasApi?["API em http://localhost:3001 (saúde em `/v1/health`, documentação em `/v1/docs`)"]:[]],s=e.vinext?`22`:`20`;return[`## Rodando localmente`,``,`Pré-requisitos: ${(t.runtime===`bun`?[...e.hasWeb?[`Node ${s}+`]:[],`Bun 1.4+`]:[`Node ${s}+`,n===`pnpm`?`pnpm 10+`:`Bun 1.2+`]).join(`, `)}${K(e,`docker-compose.yml`)?` e Docker`:``}.`,``,"```bash",...a,"```",``,...o.length?[`Depois, abra o ${o.join(` e a `)}.`,``]:[]].join(`
|
|
498
|
+
`)}function Ai(e){let{context:t,template:n}=e,r=n===`monolith`?`Monorepo com website Next.js, API NestJS e packages compartilhados`:n===`api`?`API NestJS`:e.landing?`Landing page em Next.js`:`Website em Next.js`;return[`# ${t.projectName}`,``,`${r}, gerado pelo [Rock CLI](https://www.npmjs.com/package/franchising).`,``,gi(e),``,_i(e),ki(e),vi(e),`## Scripts`,``,Oi(e),``,Si(e),wi(e),Ci(e),Ei(e),xi(e),yi(e),bi(e),`Antes de mudar runtime, deploy ou convenções, leia o [AGENTS.md](AGENTS.md).`,``].join(`
|
|
280
499
|
`).replace(/\n{3,}/g,`
|
|
281
500
|
|
|
282
|
-
`)}function
|
|
283
|
-
`:``}import ${c?`type `:``}{ ${s.join(`, `)} } from '${d}';\n${l.content.replace(/^'use client';\s*/,``)}`},u=/* @__PURE__ */ new Set;for(let t of e){let e=/^(.*?)(?:src\/)/.exec(t.path);e?.[1]!==void 0&&u.add(e[1])}for(let e of u){let n=`${e}src/`;
|
|
284
|
-
`,`${
|
|
285
|
-
|
|
286
|
-
`),[`CreateAuthDependencies`],!0);for(let t of e)s.content=s.content.replace(t,``);let t=/export type Auth = ReturnType<typeof createAuth>;/;t.test(s.content)&&(o(`${n}types/auth/instance.ts`,`import type { createAuth } from './auth';\n${t.exec(s.content)?.[0]}\n`,`${n}auth.ts`),s.content=s.content.replace(t,`export type { Auth } from './types/auth/instance';`))}let u=t.get(`${n}types/api.ts`);if(u?.content){let e=/export type AuthSession = \{[\s\S]*?\n\};/,t=e.exec(u.content);t&&(o(`${n}types/auth/session.ts`,`${t[0]}\n`,`${n}types/api.ts`),u.content=u.content.replace(e,`export type { AuthSession } from './auth/session';`))}let d=`${n}modules/queue/service.ts`;l(d,/export const queueBindings = [^\n]+;\nexport type JobQueue = [^\n]+;\nexport type Job = [^\n]+;/,`${n}types/queue/job.ts`,``,[`queueBindings`,`JobQueue`,`Job`]),l(`${n}index.ts`,/(?:\/\*\*[^\n]*\*\/\n)?export const DEFAULT_JOB_OPTIONS = \{[\s\S]*?\} as const;/,`${n}types/queue/options.ts`,``,[`DEFAULT_JOB_OPTIONS`]);let f=t.get(`${n}index.ts`);t.has(`${n}types/queue/options.ts`)&&f?.content&&(f.content=`${f.content.replace(`import { DEFAULT_JOB_OPTIONS } from './types/queue/options';
|
|
287
|
-
`,``)}\nexport { DEFAULT_JOB_OPTIONS } from './types/queue/options';\n`),l(`${n}index.ts`,/export type DatabaseOrm = '[^']+';/,`${n}types/database/orm.ts`,``,[`DatabaseOrm`],!0);let p=t.get(`${n}index.ts`);t.has(`${n}types/database/orm.ts`)&&p?.content&&(p.content=p.content.replace(/import type \{ DatabaseOrm \}/,`export type { DatabaseOrm }`));let m=t.get(d);t.has(`${n}types/queue/job.ts`)&&m?.content&&(m.content+=`
|
|
501
|
+
`)}function ji(e,t,n){let r=new Map(e.map(e=>[e.path,e])),i=n===`monolith`,a=t.packageManager,o={files:r,context:t,template:n,apiDir:i?`apps/api/`:``,webDir:i?`apps/web/`:``,hasApi:n!==`web`,hasWeb:n!==`api`,cloudflareApi:n!==`web`&&t.hosting?.api===`cloudflare`,cloudflareWeb:n!==`api`&&t.hosting?.web===`cloudflare`,landing:n!==`api`&&t.hosting?.webType===`landing`&&!t.features.betterAuth,vinext:n!==`api`&&t.hosting?.web===`cloudflare`&&t.hosting?.webAdapter!==`opennext`,queuedMessaging:t.workers.some(e=>e.kind===`messaging`),run:e=>`${a} run ${e}`,runIn:(e,t)=>z(a,e,t)};return r.delete(`CLOUDFLARE.md`),r.set(`README.md`,{path:`README.md`,content:Ai(o)}),r.set(`AGENTS.md`,{path:`AGENTS.md`,content:hi(o)}),r.set(`CLAUDE.md`,{path:`CLAUDE.md`,symlinkTarget:`AGENTS.md`}),[...r.values()]}function Mi(e){let t=new Map(e.map(e=>[e.path,{...e}])),n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map,i=c.posix,a=(e,t)=>{let n=i.relative(i.dirname(e),t);return n.startsWith(`.`)?n:`./${n}`},o=(e,r,i)=>{t.set(e,{path:e,content:r}),n.set(e,i)},s=(e,n)=>{let i=t.get(e);i?.content!==void 0&&(t.delete(e),o(n,i.content,e),r.set(e,n))},l=(e,n,r,i,s,c=!1)=>{let l=t.get(e);if(l?.content===void 0)return;let u=n.exec(l.content);if(!u)return;o(r,`${i}\n${u[0].trim()}\n`,e),l.content=l.content.replace(u[0],``);let d=a(e,r).replace(/\.[cm]?[jt]sx?$/,``);l.content=`${l.content.startsWith(`'use client';`)?`'use client';
|
|
502
|
+
`:``}import ${c?`type `:``}{ ${s.join(`, `)} } from '${d}';\n${l.content.replace(/^'use client';\s*/,``)}`},u=/* @__PURE__ */ new Set;for(let t of e){let e=/^(.*?)(?:src\/)/.exec(t.path);e?.[1]!==void 0&&u.add(e[1])}for(let e of u){let n=`${e}src/`;s(`${n}types.ts`,`${n}types/api.ts`),s(`${n}app.module.ts`,`${n}module.ts`),s(`${n}cache.service.ts`,`${n}service.ts`),s(`${n}database.service.ts`,`${n}service.ts`),s(`${n}schema.ts`,`${n}tables/index.ts`),s(`${n}modules/database/schema.ts`,`${n}tables/index.ts`);for(let e of[...t.values()]){let t=/^(.*src\/modules\/(?:auth|database|cache)\/)[^/]+\.(module|controller|service|repository)\.ts$/.exec(e.path);t&&s(e.path,`${t[1]}${t[2]}.ts`)}s(`${n}modules/queue/config.ts`,`${n}types/queue/config.ts`);let i=t.get(`${n}auth.ts`)?.content;if(i&&!i.includes(`drizzleAdapter`)&&!t.has(`${e}auth.config.ts`)){let t=i.match(/^import (?:type )?\{ DatabaseService \} from .*;$/m)?.[0]?.replace(`import type`,`import`);t&&o(`${e}auth.config.ts`,`import 'dotenv/config';\nimport { createAuth } from './src/auth';\n${t.replace(/from '([^']+)'/,(e,t)=>`from '${t.startsWith(`.`)?`./src/${t.slice(2)}`:t}'`)}\n\nexport const auth = createAuth({\n databaseService: new DatabaseService(),\n${i.includes(`messagingService:`)?` messagingService: { async sendEmail() { throw new Error('Schema generation must not send email.'); } },
|
|
503
|
+
`:``}});\n`,`${e}auth.config.ts`)}s(`${e}auth.config.ts`,`${n}types/auth/config.ts`);for(let t of[`next.config.mjs`,`postcss.config.mjs`])s(`${e}${t}`,`${n}types/config/${t}`),r.has(`${e}${t}`)&&(o(`${e}${t}`,`export { default } from './src/types/config/${t}';\n`,`${e}${t}`),r.delete(`${e}${t}`));let a=t.get(`${n}auth.ts`);if(a?.content){let e=a.content.match(/^import (?:type )?\{ (?:DatabaseService|MessagingService) \} from .*;$/gm)??[];l(`${n}auth.ts`,/export type CreateAuthDependencies = \{[\s\S]*?\};/,`${n}types/auth/dependencies.ts`,e.map(e=>e.replace(`import {`,`import type {`)).join(`
|
|
504
|
+
`),[`CreateAuthDependencies`],!0);for(let t of e)a.content=a.content.replace(t,``);let t=/export type Auth = ReturnType<typeof createAuth>;/;t.test(a.content)&&(o(`${n}types/auth/instance.ts`,`import type { createAuth } from './auth';\n${t.exec(a.content)?.[0]}\n`,`${n}auth.ts`),a.content=a.content.replace(t,`export type { Auth } from './types/auth/instance';`))}let c=t.get(`${n}types/api.ts`);if(c?.content){let e=/export type AuthSession = \{[\s\S]*?\n\};/,t=e.exec(c.content);t&&(o(`${n}types/auth/session.ts`,`${t[0]}\n`,`${n}types/api.ts`),c.content=c.content.replace(e,`export type { AuthSession } from './auth/session';`))}let u=`${n}modules/queue/service.ts`;l(u,/export const queueBindings = [^\n]+;\nexport type JobQueue = [^\n]+;\nexport type Job = [^\n]+;/,`${n}types/queue/job.ts`,``,[`queueBindings`,`JobQueue`,`Job`]);let d=t.get(u);t.has(`${n}types/queue/job.ts`)&&d?.content&&(d.content+=`
|
|
288
505
|
export type { Job, JobQueue } from '../../types/queue/job';
|
|
289
|
-
`);let
|
|
290
|
-
import { WORKER_OPTIONS, PRODUCER_OPTIONS, type QueueRedisConnection } from './types/queue/redis';
|
|
291
|
-
export type { QueueRedisConnection } from './types/queue/redis';`)}l(`${n}components/shell/app-shell.tsx`,/const groups: SidebarNavGroup\[\] = \[[\s\S]*?\n\];/,`${n}types/navigation.ts`,`import type { SidebarNavGroup } from 'franchising/ui';`,[`groups`]);let g=t.get(`${n}types/navigation.ts`);g?.content&&(g.content=g.content.replace(`const groups:`,`export const groups:`));let _=t.get(`${n}components/shell/app-shell.tsx`);_?.content&&(_.content=_.content.replace(`, type SidebarNavGroup`,``)),l(`${n}app/layout.tsx`,/const sans = Inter\([\s\S]*?\n\}\);\n\nconst mono = JetBrains_Mono\([\s\S]*?\n\}\);/,`${n}types/fonts.ts`,`import { Inter, JetBrains_Mono } from 'next/font/google';`,[`sans`,`mono`]);let v=t.get(`${n}types/fonts.ts`);v?.content&&(v.content=v.content.replace(/^const /gm,`export const `)),l(`${n}app/layout.tsx`,/export const metadata: Metadata = \{[\s\S]*?\n\};/,`${n}types/metadata.ts`,`import type { Metadata } from 'next';`,[`metadata`]);let y=t.get(`${n}app/layout.tsx`);y?.content&&(y.content=y.content.replace(`import type { Metadata } from 'next';
|
|
506
|
+
`),l(`${n}components/shell/app-shell.tsx`,/const groups: SidebarNavGroup\[\] = \[[\s\S]*?\n\];/,`${n}types/navigation.ts`,`import type { SidebarNavGroup } from 'franchising/ui';`,[`groups`]);let f=t.get(`${n}types/navigation.ts`);f?.content&&(f.content=f.content.replace(`const groups:`,`export const groups:`));let p=t.get(`${n}components/shell/app-shell.tsx`);p?.content&&(p.content=p.content.replace(`, type SidebarNavGroup`,``)),l(`${n}app/layout.tsx`,/const sans = Inter\([\s\S]*?\n\}\);\n\nconst mono = JetBrains_Mono\([\s\S]*?\n\}\);/,`${n}types/fonts.ts`,`import { Inter, JetBrains_Mono } from 'next/font/google';`,[`sans`,`mono`]);let m=t.get(`${n}types/fonts.ts`);m?.content&&(m.content=m.content.replace(/^const /gm,`export const `)),l(`${n}app/layout.tsx`,/export const metadata: Metadata = \{[\s\S]*?\n\};/,`${n}types/metadata.ts`,`import type { Metadata } from 'next';`,[`metadata`]);let h=t.get(`${n}app/layout.tsx`);h?.content&&(h.content=h.content.replace(`import type { Metadata } from 'next';
|
|
292
507
|
`,``).replace(`import { Inter, JetBrains_Mono } from 'next/font/google';
|
|
293
|
-
`,``).replace(/import \{ metadata \} from (['"][^'"]+['"]);/,`export { metadata } from $1;`));let
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
* @remarks
|
|
298
|
-
* Placeholder: \`auth:generate\`, no package da API, troca este arquivo pelas
|
|
299
|
-
* tabelas reais. Nao edite a mao; rode o comando de novo ao mudar plugins.
|
|
300
|
-
*/
|
|
301
|
-
export type AuthTablesPending = never;
|
|
302
|
-
`,`${a}/auth.ts`),s.content+=`export * from './auth';
|
|
303
|
-
`;let t=n.scripts[`auth:generate`].replace(/ --output \S+/,``);n.scripts[`auth:generate`]=`${t} --output ${i?`../../${a}`:`./${a}`}/auth.ts --yes`,e.content=`${JSON.stringify(n,null,` `)}\n`}}for(let[t,n]of r){if(!t.endsWith(`/schema.ts`))continue;let r=a(e.path,t);e.content=e.content.replaceAll(r,a(e.path,n))}}return[...t.values()]}function zr(e){return e.map(e=>e.content===void 0||!/\.(?:[cm]?[jt]sx?|jsonc?|css|prisma)$/.test(e.path)?e:{...e,content:e.content.replace(/^([\t ]+)(\*?)/gm,(e,t,n)=>{let r=n&&t.endsWith(` `)?` `:``;return`${(r?t.slice(0,-1):t).replace(/ +/g,e=>` `.repeat(Math.ceil(e.length/2)))}${r}${n}`})})}async function Br(e,t,n={},r=R){let i=t===`pnpm`?`pnpm`:`bun`;await r(i,[`install`],{cwd:e}),n.lefthook&&await r(i,[t===`pnpm`?`exec`:`run`,`lefthook`,`install`],{cwd:e})}function Vr(e){return e.map(e=>`npx --yes skills add ${e.repository} --skill ${e.skill} --global --yes`)}async function Hr(e,t=R){let n=[];for(let r of e)try{await t(`npx`,[`--yes`,`skills`,`add`,r.repository,`--skill`,r.skill,`--global`,`--yes`],{cwd:process.cwd()}),n.push({skill:r})}catch(e){n.push({skill:r,error:e})}return n}function Ur(e,t=!1,n=!1){return`import { Module } from '@nestjs/common';${t?`
|
|
304
|
-
import { TelemetryModule } from 'franchising/telemetry';
|
|
305
|
-
import { adapters } from './telemetry';`:``}
|
|
508
|
+
`,``).replace(/import \{ metadata \} from (['"][^'"]+['"]);/,`export { metadata } from $1;`));let g=t.get(`${n}app/(app)/layout.tsx`);g?.content&&(g.content=g.content.replace(`export const dynamic = 'force-dynamic';`,``))}for(let e of t.values()){if(e.content===void 0||!/\.[cm]?[jt]sx?$/.test(e.path))continue;let t=n.get(e.path)??e.path;if(e.content=e.content.replace(/((?:from\s+|import\s*\(|require\s*\(|import\s+)['"])([^'"]+)(['"])/g,(n,o,s,c)=>{let l=/^(.*?src\/)/.exec(t)?.[1],u=s.startsWith(`.`)?i.normalize(i.join(i.dirname(t),s)):s.startsWith(`@/`)&&l?`${l}${s.slice(2)}`:void 0;if(!u)return n;let d=[u,`${u}.ts`,`${u}.tsx`,`${u}.mjs`,`${u}/index.ts`].find(e=>r.has(e))??u,f=r.get(d)??d;if(f===u&&e.path===t)return n;let p=/\.[cm]?[jt]sx?$/.test(s)?f:f.replace(/(?:\/index)?\.[cm]?[jt]sx?$/,``);return`${o}${s.startsWith(`@/`)&&l?`@/${p.slice(l.length)}`:a(e.path,p)}${c}`}),e.path.endsWith(`drizzle.config.ts`))for(let[t,n]of r){let r=a(e.path,t);e.content=e.content.replaceAll(`'${r}'`,`'${a(e.path,n)}'`)}}for(let e of t.values()){if(e.path.endsWith(`.md`)&&e.content!==void 0)for(let[t,n]of r)e.content=e.content.replaceAll(t,n);if(!e.path.endsWith(`package.json`)||e.content===void 0)continue;let n=JSON.parse(e.content);if(n.scripts?.[`auth:generate`]){let r=`./src/types/auth/config.ts`;if(n.scripts[`auth:generate`]=n.scripts[`auth:generate`].includes(`--config`)?n.scripts[`auth:generate`].replace(/--config \S+/,`--config ${r}`):`${n.scripts[`auth:generate`]} --config ${r}`,e.content=`${JSON.stringify(n,null,` `)}\n`,e.path===`apps/api/package.json`){let r=JSON.parse(t.get(`packages/database/package.json`)?.content??`{}`);if(!n.scripts[`auth:generate`].includes(r.name)){let t=n.packageManager?.startsWith(`pnpm@`)?`pnpm`:`bun`;n.scripts[`auth:generate`]=`${z(t,r.name,`build`)} && ${n.scripts[`auth:generate`]}`,e.content=`${JSON.stringify(n,null,` `)}\n`}}}for(let[t,n]of r){if(!t.endsWith(`/schema.ts`))continue;let r=a(e.path,t);e.content=e.content.replaceAll(r,a(e.path,n))}}return[...t.values()]}function Ni(e){return e.map(e=>e.content===void 0||!/\.(?:[cm]?[jt]sx?|jsonc?|css|prisma)$/.test(e.path)?e:{...e,content:e.content.replace(/^([\t ]+)(\*?)/gm,(e,t,n)=>{let r=n&&t.endsWith(` `)?` `:``;return`${(r?t.slice(0,-1):t).replace(/ +/g,e=>` `.repeat(Math.ceil(e.length/2)))}${r}${n}`})})}async function Pi(e,t,n={},r=I){let i=t===`pnpm`?`pnpm`:`bun`;await r(i,[`install`],{cwd:e}),n.lefthook&&await r(i,[t===`pnpm`?`exec`:`run`,`lefthook`,`install`],{cwd:e})}function Fi(e){return e.map(e=>`npx --yes skills add ${e.repository} --skill ${e.skill} --global --yes`)}async function Ii(e,t=I){let n=[];for(let r of e)try{await t(`npx`,[`--yes`,`skills`,`add`,r.repository,`--skill`,r.skill,`--global`,`--yes`],{cwd:process.cwd()}),n.push({skill:r})}catch(e){n.push({skill:r,error:e})}return n}function Li(e,t=!1,n=!1,r=`./shared/observability`){return`import { Module } from '@nestjs/common';
|
|
509
|
+
import { ErrorsModule } from 'franchising/http';${t?`
|
|
510
|
+
import { Telemetry, TelemetryModule } from 'franchising/telemetry';
|
|
511
|
+
import { adapters } from '${r}';`:``}
|
|
306
512
|
import { CacheModule } from './modules/cache/cache.module';
|
|
307
513
|
import { DatabaseModule } from './modules/database/database.module';
|
|
308
514
|
import { HealthModule } from './modules/health/module';
|
|
@@ -313,16 +519,36 @@ ${e?`import { AppAuthModule } from './modules/auth/auth.module';`:``}
|
|
|
313
519
|
imports: [${t?`
|
|
314
520
|
/*
|
|
315
521
|
* A lista de adapters e a mesma do bootstrap: o modulo configura a facade
|
|
316
|
-
* injetada e a integracao HTTP, e nao os exportadores.
|
|
522
|
+
* injetada e a integracao HTTP, e nao os exportadores. O filtro do
|
|
523
|
+
* telemetry fica desligado porque o \`ErrorFilter\` do franchising/http e
|
|
524
|
+
* quem monta o envelope de erro; dois filtros globais disputariam a
|
|
525
|
+
* resposta.
|
|
317
526
|
*/
|
|
318
527
|
TelemetryModule.forRoot({
|
|
319
528
|
adapters,
|
|
320
529
|
logging: { excludePaths: ['/v1/health'] },
|
|
530
|
+
http: { filter: false },
|
|
531
|
+
}),
|
|
532
|
+
/*
|
|
533
|
+
* O \`onError\` devolve ao error tracking o que o filtro do telemetry
|
|
534
|
+
* reportava: 5xx e 429, que sao falha do servidor ou limite estourado.
|
|
535
|
+
*/
|
|
536
|
+
ErrorsModule.forRootAsync({
|
|
537
|
+
inject: [Telemetry],
|
|
538
|
+
useFactory: (telemetry: Telemetry) => ({
|
|
539
|
+
onError: (exception, { status }) => {
|
|
540
|
+
if (status >= 500 || status === 429)
|
|
541
|
+
telemetry.captureException(exception, { statusCode: status });
|
|
542
|
+
},
|
|
543
|
+
}),
|
|
321
544
|
}),
|
|
322
|
-
|
|
545
|
+
`:`
|
|
546
|
+
/* Converte tudo que for lancado no envelope \`{ ok: false, error }\`. */
|
|
547
|
+
ErrorsModule.forRoot(),
|
|
548
|
+
`}CacheModule, DatabaseModule${n?`, MessagingModule`:``}, HealthModule${e?`, AppAuthModule`:``}],
|
|
323
549
|
})
|
|
324
550
|
export class AppModule {}
|
|
325
|
-
`}function
|
|
551
|
+
`}function Ri(e,t=!1){return`import { Module } from '@nestjs/common';
|
|
326
552
|
import { AuthModule as BetterAuthModule } from '@thallesp/nestjs-better-auth';
|
|
327
553
|
import { createAuth } from '../../auth';
|
|
328
554
|
import { DatabaseService } from '${e}';
|
|
@@ -346,7 +572,8 @@ ${t?` messagingService: MessagingService,`:``}
|
|
|
346
572
|
controllers: [AuthSessionController],
|
|
347
573
|
})
|
|
348
574
|
export class AppAuthModule {}
|
|
349
|
-
`}function
|
|
575
|
+
`}function zi(){return`import { Controller, Get } from '@nestjs/common';
|
|
576
|
+
import { ok } from 'franchising/http';
|
|
350
577
|
import {
|
|
351
578
|
AllowAnonymous,
|
|
352
579
|
Session,
|
|
@@ -357,19 +584,19 @@ import {
|
|
|
357
584
|
export class AuthSessionController {
|
|
358
585
|
@Get('me')
|
|
359
586
|
getCurrentSession(@Session() session: UserSession) {
|
|
360
|
-
return session;
|
|
587
|
+
return ok(session);
|
|
361
588
|
}
|
|
362
589
|
|
|
363
590
|
@Get('public')
|
|
364
591
|
@AllowAnonymous()
|
|
365
592
|
getPublicSessionInfo() {
|
|
366
|
-
return {
|
|
593
|
+
return ok({
|
|
367
594
|
authenticated: false,
|
|
368
595
|
provider: 'better-auth',
|
|
369
|
-
};
|
|
596
|
+
});
|
|
370
597
|
}
|
|
371
598
|
}
|
|
372
|
-
`}const
|
|
599
|
+
`}const Bi=[{id:`organization`,label:`Organization`,hint:`Organizacoes, membros, convites e papeis.`,serverImport:{name:`organization`,from:`better-auth/plugins`},clientImport:{name:`organizationClient`,from:`better-auth/client/plugins`},config:` organization({
|
|
373
600
|
allowUserToCreateOrganization: true,
|
|
374
601
|
creatorRole: 'owner',
|
|
375
602
|
}),`,needsMigration:!0},{id:`admin`,label:`Admin`,hint:`Papel de administrador, banimento e impersonacao.`,serverImport:{name:`admin`,from:`better-auth/plugins`},clientImport:{name:`adminClient`,from:`better-auth/client/plugins`},config:` admin({
|
|
@@ -389,12 +616,12 @@ export class AuthSessionController {
|
|
|
389
616
|
}),`,needsMigration:!1},{id:`rockfellerSso`,label:`Rockfeller SSO`,hint:`Login pela Conta Rockfeller com franchising/sso.`,serverImport:{name:`rockfeller`,from:`franchising/sso`},clientImport:{name:`rockfellerClient`,from:`franchising/sso/client`},config:` rockfeller({
|
|
390
617
|
clientId: env.ROCKFELLER_CLIENT_ID,
|
|
391
618
|
clientSecret: env.ROCKFELLER_CLIENT_SECRET,
|
|
392
|
-
}),`,needsMigration:!1,packageName:
|
|
393
|
-
`)}function
|
|
394
|
-
`)}\n ],`}function
|
|
395
|
-
`)}function
|
|
396
|
-
`)}function
|
|
397
|
-
`)}function
|
|
619
|
+
}),`,needsMigration:!1,packageName:wr,packageVersion:Tr,peers:kr}],Vi=Bi.map(e=>({value:e.id,label:e.label,hint:e.hint}));function Hi(e){return Bi.filter(t=>e.includes(t.id))}function Ui(e){let t=/* @__PURE__ */ new Map;for(let n of e)t.set(n.from,[...t.get(n.from)??[],n.name]);return[...t.entries()].map(([e,t])=>`import { ${t.sort().join(`, `)} } from '${e}';`).join(`
|
|
620
|
+
`)}function Wi(e){let t=Hi(e);return t.length===0?``:Ui(t.map(e=>e.serverImport))}function Gi(e){let t=Hi(e).filter(e=>e.clientImport);return t.length===0?``:Ui(t.map(e=>e.clientImport))}function Ki(e){let t=Hi(e).filter(e=>e.config);return t.length===0?``:` plugins: [\n${t.map(e=>e.config).join(`
|
|
621
|
+
`)}\n ],`}function qi(e){return Hi(e).filter(e=>e.clientImport).map(e=>` ${e.clientImport?.name}(),`).join(`
|
|
622
|
+
`)}function Ji(e,t,n=`server`){return Object.fromEntries(Hi(e).filter(e=>e.packageName).flatMap(e=>[[e.packageName,e.packageVersion??t],...n===`server`?Object.entries(e.peers??{}):[]]))}function Yi(e){return Hi(e).some(e=>e.needsMigration)?[`npx @better-auth/cli generate`,`npx @better-auth/cli migrate`]:[]}function Xi(e){return e.flatMap(e=>e===`google`?[` GOOGLE_CLIENT_ID: str({`,` desc: 'Google OAuth client id',`,` devDefault: '',`,` }),`,` GOOGLE_CLIENT_SECRET: str({`,` desc: 'Google OAuth client secret',`,` devDefault: '',`,` }),`]:e===`github`?[` GITHUB_CLIENT_ID: str({`,` desc: 'GitHub OAuth client id',`,` devDefault: '',`,` }),`,` GITHUB_CLIENT_SECRET: str({`,` desc: 'GitHub OAuth client secret',`,` devDefault: '',`,` }),`]:e===`discord`?[` DISCORD_CLIENT_ID: str({`,` desc: 'Discord OAuth client id',`,` devDefault: '',`,` }),`,` DISCORD_CLIENT_SECRET: str({`,` desc: 'Discord OAuth client secret',`,` devDefault: '',`,` }),`]:[]).join(`
|
|
623
|
+
`)}function Zi(e){return e.flatMap(e=>e===`google`?[`GOOGLE_CLIENT_ID=""`,`GOOGLE_CLIENT_SECRET=""`]:e===`github`?[`GITHUB_CLIENT_ID=""`,`GITHUB_CLIENT_SECRET=""`]:e===`discord`?[`DISCORD_CLIENT_ID=""`,`DISCORD_CLIENT_SECRET=""`]:[]).join(`
|
|
624
|
+
`)}function Qi(e,t=!1,n=!0){let r=t?` `:``,i=[];e.includes(`emailAndPassword`)&&i.push(`${r} emailAndPassword: {
|
|
398
625
|
${r} enabled: true,
|
|
399
626
|
${n?`${r} sendResetPassword: async ({ user, url }) => {
|
|
400
627
|
${r} await messagingService.sendEmail({
|
|
@@ -410,11 +637,9 @@ ${r} },`}).join(`
|
|
|
410
637
|
`);i.push(`${r} socialProviders: {
|
|
411
638
|
${e}
|
|
412
639
|
${r} },`)}return i.join(`
|
|
413
|
-
`)}function
|
|
640
|
+
`)}function $i(e,t,n,r=[],i=!1){if(r.includes(`magicLink`)&&!i)throw Error(`Magic Link requires the optional messaging module. Enable messaging to send login links.`);let a=i&&(t.includes(`emailAndPassword`)||r.includes(`magicLink`)),o=Wi(r),s=Ki(r),c=e===`prisma`?`import { prismaAdapter } from '@better-auth/prisma-adapter';`:`import { drizzleAdapter } from '@better-auth/drizzle-adapter';`,l=e===`prisma`?` database: prismaAdapter(databaseService.client, {
|
|
414
641
|
provider: 'postgresql',
|
|
415
|
-
})
|
|
416
|
-
provider: 'pg',
|
|
417
|
-
}),`;return`import { betterAuth } from 'better-auth';
|
|
642
|
+
}),`:" /*\n * Tabelas no plural (`users`, `sessions`...), escritas a mao em\n * `tables/auth/`: o adapter procura o modelo `user` como `users`.\n */\n database: drizzleAdapter(databaseService.client, {\n provider: 'pg',\n usePlural: true,\n }),";return`import { betterAuth } from 'better-auth';
|
|
418
643
|
${c}
|
|
419
644
|
${o?`${o}\n`:``}${n}
|
|
420
645
|
${i?`import type { MessagingService } from './modules/messaging/service';`:``}
|
|
@@ -444,15 +669,15 @@ ${l}
|
|
|
444
669
|
baseURL: env.BETTER_AUTH_URL,
|
|
445
670
|
basePath: '/v1/auth',
|
|
446
671
|
trustedOrigins: [env.CLIENT_ORIGIN],
|
|
447
|
-
${
|
|
672
|
+
${Qi(t,!0,i)}${s?`\n${s}`:``}
|
|
448
673
|
});
|
|
449
674
|
}
|
|
450
675
|
|
|
451
676
|
/** Instancia ja estreitada pelos plugins escolhidos. */
|
|
452
677
|
export type Auth = ReturnType<typeof createAuth>;
|
|
453
|
-
`}function
|
|
454
|
-
`)}function
|
|
455
|
-
`)}function
|
|
678
|
+
`}function ea(e,t){return[Xi(e),...t.includes(`rockfellerSso`)?[` ROCKFELLER_CLIENT_ID: str({ desc: 'Rockfeller SSO client ID', devDefault: '' }),`,` ROCKFELLER_CLIENT_SECRET: str({ desc: 'Rockfeller SSO client secret', devDefault: '' }),`]:[]].filter(Boolean).join(`
|
|
679
|
+
`)}function ta(e,t){return[Zi(e),...t.includes(`rockfellerSso`)?[`ROCKFELLER_CLIENT_ID=""`,`ROCKFELLER_CLIENT_SECRET=""`]:[]].filter(Boolean).join(`
|
|
680
|
+
`)}function na(e){return e??`drizzle`}function ra(){return`generator client {
|
|
456
681
|
provider = "prisma-client-js"
|
|
457
682
|
}
|
|
458
683
|
|
|
@@ -466,7 +691,7 @@ model User {
|
|
|
466
691
|
email String @unique
|
|
467
692
|
createdAt DateTime @default(now())
|
|
468
693
|
}
|
|
469
|
-
`}function
|
|
694
|
+
`}function ia(){return`import 'dotenv/config';
|
|
470
695
|
import { defineConfig, env } from 'prisma/config';
|
|
471
696
|
|
|
472
697
|
export default defineConfig({
|
|
@@ -479,27 +704,83 @@ export default defineConfig({
|
|
|
479
704
|
url: env('DATABASE_URL'),
|
|
480
705
|
},
|
|
481
706
|
});
|
|
482
|
-
`}function
|
|
483
|
-
|
|
484
|
-
export const users = pgTable('users', {
|
|
485
|
-
id: uuid('id').defaultRandom().primaryKey(),
|
|
486
|
-
email: text('email').notNull().unique(),
|
|
487
|
-
createdAt: timestamp('created_at', { withTimezone: true })
|
|
488
|
-
.defaultNow()
|
|
489
|
-
.notNull(),
|
|
490
|
-
});
|
|
491
|
-
`}function vi(e){return`import { defineConfig } from 'drizzle-kit';
|
|
707
|
+
`}function aa(e){return`import { defineConfig } from 'drizzle-kit';
|
|
492
708
|
import { env } from '${e.envImport}';
|
|
493
709
|
|
|
494
710
|
export default defineConfig({
|
|
495
711
|
schema: '${e.schemaPath}',
|
|
496
712
|
out: './drizzle',
|
|
497
713
|
dialect: 'postgresql',
|
|
714
|
+
casing: 'snake_case',
|
|
498
715
|
dbCredentials: {
|
|
499
716
|
url: env.DATABASE_URL,
|
|
500
717
|
},
|
|
501
718
|
});
|
|
502
|
-
`}
|
|
719
|
+
`}const q=`id: text().primaryKey(),`,J=`createdAt: timestamp({ withTimezone: true }).defaultNow().notNull(),`,oa=`updatedAt: timestamp({ withTimezone: true })
|
|
720
|
+
.defaultNow()
|
|
721
|
+
.$onUpdate(() => new Date())
|
|
722
|
+
.notNull(),`;function sa(e){let[t=``,...n]=e.split(`
|
|
723
|
+
`);return[` ${t.trim()}`,...n.map(e=>` ${e.trim()}`)].join(`
|
|
724
|
+
`)}function Y(e){let t=[.../* @__PURE__ */ new Set([`pgTable`,...e.imports,...e.indexes?[`index`]:[]])].sort(),n=Object.entries(e.references??{}).map(([e,t])=>`import { ${e} } from '${t}';\n`).join(``),r=e.indexes?`\n (table) => [\n${e.indexes.map(e=>` ${e},`).join(`
|
|
725
|
+
`)}\n ],`:``;return`import { ${t.join(`, `)} } from 'drizzle-orm/pg-core';
|
|
726
|
+
${n}
|
|
727
|
+
/** ${e.doc} */
|
|
728
|
+
export const ${e.exportName} = pgTable(
|
|
729
|
+
'${e.name}',
|
|
730
|
+
{
|
|
731
|
+
${e.columns.map(sa).join(`
|
|
732
|
+
`)}
|
|
733
|
+
},${r}
|
|
734
|
+
);
|
|
735
|
+
`}function X(e){return`.references(() => ${e}.id, { onDelete: 'cascade' })`}function ca(e){let t=new Set(e.authPlugins),n=t.has(`admin`),r=t.has(`twoFactor`),i=t.has(`organization`),a=[{path:`auth/users.ts`,exportName:`users`,content:Y({name:`users`,exportName:`users`,doc:`Usuarios do Better Auth.`,imports:[`boolean`,`text`,`timestamp`],columns:[q,`name: text().notNull(),`,`email: text().notNull().unique(),`,`emailVerified: boolean().default(false).notNull(),`,`image: text(),`,...n?[`role: text(),`,`banned: boolean().default(false),`,`banReason: text(),`,`banExpires: timestamp({ withTimezone: true }),`]:[],...r?[`twoFactorEnabled: boolean().default(false),`]:[],J,oa]})},{path:`auth/sessions.ts`,exportName:`sessions`,content:Y({name:`sessions`,exportName:`sessions`,doc:`Sessoes ativas, uma por login.`,imports:[`text`,`timestamp`],references:{users:`./users`},columns:[q,`expiresAt: timestamp({ withTimezone: true }).notNull(),`,`token: text().notNull().unique(),`,`ipAddress: text(),`,`userAgent: text(),`,`userId: text()\n .notNull()\n ${X(`users`)},`,...i?[`activeOrganizationId: text(),`]:[],...n?[`impersonatedBy: text(),`]:[],J,oa],indexes:[`index('sessions_user_id_idx').on(table.userId)`]})},{path:`auth/accounts.ts`,exportName:`accounts`,content:Y({name:`accounts`,exportName:`accounts`,doc:`Contas de login (senha ou provedor externo) de cada usuario.`,imports:[`text`,`timestamp`],references:{users:`./users`},columns:[q,`accountId: text().notNull(),`,`providerId: text().notNull(),`,`userId: text()\n .notNull()\n ${X(`users`)},`,`accessToken: text(),`,`refreshToken: text(),`,`idToken: text(),`,`accessTokenExpiresAt: timestamp({ withTimezone: true }),`,`refreshTokenExpiresAt: timestamp({ withTimezone: true }),`,`scope: text(),`,`password: text(),`,J,oa],indexes:[`index('accounts_user_id_idx').on(table.userId)`]})},{path:`auth/verifications.ts`,exportName:`verifications`,content:Y({name:`verifications`,exportName:`verifications`,doc:`Tokens de verificacao (e-mail, reset de senha, magic link).`,imports:[`text`,`timestamp`],columns:[q,`identifier: text().notNull(),`,`value: text().notNull(),`,`expiresAt: timestamp({ withTimezone: true }).notNull(),`,J,oa],indexes:[`index('verifications_identifier_idx').on(table.identifier)`]})}];return i&&a.push({path:`auth/organizations.ts`,exportName:`organizations`,content:Y({name:`organizations`,exportName:`organizations`,doc:`Organizacoes do plugin organization.`,imports:[`text`,`timestamp`],columns:[q,`name: text().notNull(),`,`slug: text().notNull().unique(),`,`logo: text(),`,`metadata: text(),`,J]})},{path:`auth/members.ts`,exportName:`members`,content:Y({name:`members`,exportName:`members`,doc:`Membros de cada organizacao, com o papel.`,imports:[`text`,`timestamp`],references:{organizations:`./organizations`,users:`./users`},columns:[q,`organizationId: text()\n .notNull()\n ${X(`organizations`)},`,`userId: text()\n .notNull()\n ${X(`users`)},`,`role: text().default('member').notNull(),`,J],indexes:[`index('members_organization_id_idx').on(table.organizationId)`,`index('members_user_id_idx').on(table.userId)`]})},{path:`auth/invitations.ts`,exportName:`invitations`,content:Y({name:`invitations`,exportName:`invitations`,doc:`Convites pendentes para entrar numa organizacao.`,imports:[`text`,`timestamp`],references:{organizations:`./organizations`,users:`./users`},columns:[q,`organizationId: text()\n .notNull()\n ${X(`organizations`)},`,`email: text().notNull(),`,`role: text(),`,`status: text().default('pending').notNull(),`,`expiresAt: timestamp({ withTimezone: true }).notNull(),`,`inviterId: text()\n .notNull()\n ${X(`users`)},`,J],indexes:[`index('invitations_organization_id_idx').on(table.organizationId)`,`index('invitations_email_idx').on(table.email)`]})}),r&&a.push({path:`auth/two-factors.ts`,exportName:`twoFactors`,content:Y({name:`two_factors`,exportName:`twoFactors`,doc:`Segredo TOTP e codigos de backup do plugin twoFactor.`,imports:[`boolean`,`integer`,`text`,`timestamp`],references:{users:`./users`},columns:[q,`secret: text().notNull(),`,`backupCodes: text().notNull(),`,`userId: text()\n .notNull()\n ${X(`users`)},`,`verified: boolean().default(true),`,`failedVerificationCount: integer().default(0),`,`lockedUntil: timestamp({ withTimezone: true }),`],indexes:[`index('two_factors_secret_idx').on(table.secret)`,`index('two_factors_user_id_idx').on(table.userId)`]})}),t.has(`apiKey`)&&a.push({path:`auth/apikeys.ts`,exportName:`apikeys`,content:Y({name:`apikeys`,exportName:`apikeys`,doc:"Chaves de API do plugin `@better-auth/api-key` (so o hash fica salvo).",imports:[`boolean`,`integer`,`text`,`timestamp`],columns:[q,`configId: text().default('default').notNull(),`,`name: text(),`,`start: text(),`,`prefix: text(),`,`key: text().notNull(),`,`referenceId: text().notNull(),`,`refillInterval: integer(),`,`refillAmount: integer(),`,`lastRefillAt: timestamp({ withTimezone: true }),`,`enabled: boolean().default(true),`,`rateLimitEnabled: boolean().default(true),`,`rateLimitTimeWindow: integer().default(86_400_000),`,`rateLimitMax: integer().default(10),`,`requestCount: integer().default(0),`,`remaining: integer(),`,`lastRequest: timestamp({ withTimezone: true }),`,`expiresAt: timestamp({ withTimezone: true }),`,`permissions: text(),`,`metadata: text(),`,J,oa],indexes:[`index('apikeys_config_id_idx').on(table.configId)`,`index('apikeys_reference_id_idx').on(table.referenceId)`,`index('apikeys_key_idx').on(table.key)`]})}),a}function la(){return{path:`auth/users.ts`,exportName:`users`,content:Y({name:`users`,exportName:`users`,doc:`Tabela de exemplo: troque pelas tabelas do produto.`,imports:[`text`,`timestamp`,`uuid`],columns:[`id: uuid().defaultRandom().primaryKey(),`,`email: text().notNull().unique(),`,J]})}}function ua(){return[{path:`webhooks/endpoints.ts`,exportName:`webhookEndpoints`,content:Y({name:`webhook_endpoints`,exportName:`webhookEndpoints`,doc:`Destinos de webhook, um por URL cadastrada pelo dono.`,imports:[`boolean`,`text`,`timestamp`,`uuid`],columns:[`id: uuid().defaultRandom().primaryKey(),`,`ownerId: text().notNull(),`,`url: text().notNull(),`,"/** Segredo `whsec_` cifrado com AES-256-GCM (`WEBHOOK_SECRETS_KEY`). */",`secret: text().notNull(),`,`eventTypes: text().array().notNull(),`,`enabled: boolean().default(true).notNull(),`,J,oa],indexes:[`index('webhook_endpoints_owner_id_idx').on(table.ownerId)`]})},{path:`webhooks/outbox.ts`,exportName:`webhookOutbox`,content:Y({name:`webhook_outbox`,exportName:`webhookOutbox`,doc:"Eventos esperando entrega: a API grava na transacao do negocio e o worker `webhooks` despacha os pendentes.",imports:[`jsonb`,`text`,`timestamp`,`uuid`],columns:[`id: uuid().defaultRandom().primaryKey(),`,`ownerId: text().notNull(),`,`eventType: text().notNull(),`,`payload: jsonb().notNull(),`,J,`dispatchedAt: timestamp({ withTimezone: true }),`],indexes:[`index('webhook_outbox_pending_idx').on(table.dispatchedAt, table.createdAt)`]})},{path:`webhooks/deliveries.ts`,exportName:`webhookDeliveries`,content:Y({name:`webhook_deliveries`,exportName:`webhookDeliveries`,doc:`Cada tentativa de entrega, com o status que o receptor respondeu.`,imports:[`integer`,`text`,`timestamp`,`uuid`],references:{webhookEndpoints:`./endpoints`},columns:[`id: uuid().defaultRandom().primaryKey(),`,`endpointId: uuid()\n .notNull()\n ${X(`webhookEndpoints`)},`,`messageId: uuid().notNull(),`,`eventType: text().notNull(),`,`attempt: integer().notNull(),`,`status: text().$type<'succeeded' | 'failed'>().notNull(),`,`responseStatus: integer(),`,`error: text(),`,J],indexes:[`index('webhook_deliveries_endpoint_id_idx').on(table.endpointId, table.createdAt)`]})}]}function da(e){let t=new Set(e.authPlugins),n=[],r=[];if(e.betterAuth){let e=t.has(`organization`),i=t.has(`twoFactor`),a=[`accounts`,`sessions`,`users`,...e?[`invitations`,`members`,`organizations`]:[],...i?[`twoFactors`]:[]].sort();r.push(`import { ${a.join(`, `)} } from './auth';`),n.push(`export const usersRelations = relations(users, ({ many }) => ({
|
|
736
|
+
sessions: many(sessions),
|
|
737
|
+
accounts: many(accounts),${e?`
|
|
738
|
+
members: many(members),
|
|
739
|
+
invitations: many(invitations),`:``}${i?`
|
|
740
|
+
twoFactors: many(twoFactors),`:``}
|
|
741
|
+
}));`,`export const sessionsRelations = relations(sessions, ({ one }) => ({
|
|
742
|
+
user: one(users, { fields: [sessions.userId], references: [users.id] }),
|
|
743
|
+
}));`,`export const accountsRelations = relations(accounts, ({ one }) => ({
|
|
744
|
+
user: one(users, { fields: [accounts.userId], references: [users.id] }),
|
|
745
|
+
}));`),e&&n.push(`export const organizationsRelations = relations(organizations, ({ many }) => ({
|
|
746
|
+
members: many(members),
|
|
747
|
+
invitations: many(invitations),
|
|
748
|
+
}));`,`export const membersRelations = relations(members, ({ one }) => ({
|
|
749
|
+
organization: one(organizations, {
|
|
750
|
+
fields: [members.organizationId],
|
|
751
|
+
references: [organizations.id],
|
|
752
|
+
}),
|
|
753
|
+
user: one(users, { fields: [members.userId], references: [users.id] }),
|
|
754
|
+
}));`,`export const invitationsRelations = relations(invitations, ({ one }) => ({
|
|
755
|
+
organization: one(organizations, {
|
|
756
|
+
fields: [invitations.organizationId],
|
|
757
|
+
references: [organizations.id],
|
|
758
|
+
}),
|
|
759
|
+
inviter: one(users, { fields: [invitations.inviterId], references: [users.id] }),
|
|
760
|
+
}));`),i&&n.push(`export const twoFactorsRelations = relations(twoFactors, ({ one }) => ({
|
|
761
|
+
user: one(users, { fields: [twoFactors.userId], references: [users.id] }),
|
|
762
|
+
}));`)}if(e.webhooks&&(r.push(`import { webhookDeliveries, webhookEndpoints } from './webhooks';`),n.push(`export const webhookEndpointsRelations = relations(webhookEndpoints, ({ many }) => ({
|
|
763
|
+
deliveries: many(webhookDeliveries),
|
|
764
|
+
}));`,`export const webhookDeliveriesRelations = relations(webhookDeliveries, ({ one }) => ({
|
|
765
|
+
endpoint: one(webhookEndpoints, {
|
|
766
|
+
fields: [webhookDeliveries.endpointId],
|
|
767
|
+
references: [webhookEndpoints.id],
|
|
768
|
+
}),
|
|
769
|
+
}));`)),n.length!==0)return`/**
|
|
770
|
+
* Relations de todas as tabelas.
|
|
771
|
+
*
|
|
772
|
+
* @remarks
|
|
773
|
+
* Ficam aqui, e nao ao lado de cada tabela, para uma tabela nunca importar a
|
|
774
|
+
* outra so por causa da consulta relacional (\`db.query.*.findMany({ with })\`).
|
|
775
|
+
*/
|
|
776
|
+
import { relations } from 'drizzle-orm';
|
|
777
|
+
${r.join(`
|
|
778
|
+
`)}
|
|
779
|
+
|
|
780
|
+
${n.join(`
|
|
781
|
+
|
|
782
|
+
`)}
|
|
783
|
+
`}function fa(e){let t=[...e.betterAuth?ca(e):[la()],...e.webhooks?ua():[]],n=[...new Set(t.map(e=>e.path.split(`/`)[0]))],r=da(e),i=[...t.map(({path:e,content:t})=>({path:e,content:t})),...n.map(e=>({path:`${e}/index.ts`,content:t.filter(t=>t.path.startsWith(`${e}/`)).map(t=>`export { ${t.exportName} } from './${t.path.slice(e.length+1,-3)}';\n`).join(``)})),...r?[{path:`relations.ts`,content:r}]:[]];return{index:[...n,...r?[`relations`]:[]].map(t=>`export * from '${e.schemaToTables}/${t}';\n`).join(``),files:i}}function pa(e){let{index:t,files:n}=fa(e);return[{path:e.schemaPath,content:t},...n.map(t=>({path:`${e.tablesDir}/${t.path}`,content:t.content}))]}function ma(){return`{
|
|
503
784
|
"$schema": "https://json.schemastore.org/nest-cli",
|
|
504
785
|
"collection": "@nestjs/schematics",
|
|
505
786
|
"sourceRoot": "src",
|
|
@@ -508,9 +789,30 @@ export default defineConfig({
|
|
|
508
789
|
"typeCheck": false
|
|
509
790
|
}
|
|
510
791
|
}
|
|
511
|
-
`}function
|
|
512
|
-
|
|
513
|
-
|
|
792
|
+
`}function ha(){return H({extends:`./tsconfig.json`,compilerOptions:{tsBuildInfoFile:`./dist/tsconfig.build.tsbuildinfo`},exclude:[`node_modules`,`dist`,`test`,`**/*.spec.ts`]})}function ga(e=`bun`){return e===`pnpm`?{module:`nodenext`,moduleResolution:`nodenext`,esm:!1}:{module:`ESNext`,moduleResolution:`bundler`,esm:!0}}function _a(e={}){let t=ga(e.packageManager);return H({...e.extends?{extends:e.extends}:{},compilerOptions:{module:t.module,moduleResolution:t.moduleResolution,esModuleInterop:!0,isolatedModules:!0,declaration:!0,removeComments:!0,emitDecoratorMetadata:!0,experimentalDecorators:!0,allowSyntheticDefaultImports:!0,target:`ES2023`,sourceMap:!0,outDir:`./dist`,baseUrl:`./`,types:e.runtime===`bun`?[`bun`]:[`node`],incremental:!0,skipLibCheck:!0,strict:!0,forceConsistentCasingInFileNames:!0,paths:{"@/*":[`./src/*`]}},include:[`src/**/*.ts`],exclude:[`node_modules`,`dist`]})}function va(e){return{has:t=>t===`authModule`&&e.authModule||t===`inlineAuth`&&e.inlineAuth||t===`messaging`&&!!e.messaging||t===`telemetry`&&e.telemetry||e.telemetry&&t===e.telemetryAdapter,tokens:{__ROCK_PROJECT_SLUG__:e.projectSlug,__ROCK_PROJECT_NAME__:e.projectName,__ROCK_OBSERVABILITY__:e.observability??`./shared/observability`}}}function ya(e){let t=va(e);return[...e.telemetry&&!e.observability?zr({prefix:e.prefix?`${e.prefix}/`:``,telemetryAdapter:e.telemetryAdapter}):[],...U({dir:`api`,prefix:e.prefix,entries:[{source:`src/main.ts`},{source:`src/types.ts`},{source:`src/modules/messaging/module.ts`,condition:()=>!!e.messaging},{source:`src/modules/messaging/service.ts`,condition:()=>!!e.messaging},{source:`src/shared/http/errors.ts`},{source:`src/modules/health/module.ts`},{source:`src/modules/health/controller.ts`},{source:`src/modules/health/service.ts`},{source:`src/modules/health/dto/response.dto.ts`}]},t)]}function ba(e,t){return e.map(e=>e.content===void 0?e:!t&&e.path.endsWith(`/env.ts`)&&!e.path.startsWith(`apps/workers/`)?{...e,content:e.content.replace(/^ {2}MESSAGING_(?:API_KEY|FROM):.*\n/gm,``)}:t&&/^(?:apps\/api\/)?\.env(?:\.example)?$/.test(e.path)?{...e,content:`${e.content.trimEnd()}\nMESSAGING_API_KEY=""\nMESSAGING_FROM=""\n`}:e)}function xa(e){let t=/* @__PURE__ */ new Set;return e.hasWeb&&t.add(`hasWeb`),e.hasApi&&t.add(`hasApi`),e.ultracite&&t.add(`ultracite`),e.commitlint&&t.add(`commitlint`),{has:e=>t.has(e),tokens:{__ROCK_PM__:e.packageManager,__ROCK_PM_EXEC__:e.packageManager===`pnpm`?`pnpm exec`:`bunx`}}}function Sa(e){return U({dir:`root`,entries:[{source:`dot-oxlintrc.json`},{source:`dot-oxfmtrc.json`},{source:`dot-editorconfig`,condition:()=>e.editorconfig},{source:`lefthook.yml`,condition:()=>e.lefthook},{source:`dot-dockerignore`,condition:()=>e.dockerignore}]},xa(e))}function Ca(){return{"@stylistic/eslint-plugin":`^5.10.0`,oxfmt:`^0.70.0`,oxlint:`^1.85.0`,ultracite:`^7.12.0`}}const Z=[`monolith`,`web`,`api`],wa=[`monolith`,`api`],Ta=[{id:`ultracite`,group:`quality`,label:`Ultracite`,hint:`Lint e format com oxlint e oxfmt.`,templates:Z,defaultSelected:!0},{id:`lefthook`,group:`quality`,label:`Lefthook`,hint:`Git hooks e script prepare.`,templates:Z,defaultSelected:!0},{id:`commitlint`,group:`quality`,label:`Commitlint`,hint:`Validacao de mensagens de commit.`,templates:Z,defaultSelected:!0},{id:`editorconfig`,group:`quality`,label:`EditorConfig`,hint:`Padroes basicos de edicao.`,templates:Z,defaultSelected:!0},{id:`dockerfile`,group:`deploy`,label:`Dockerfile`,hint:`Imagem/container da app.`,templates:Z,defaultSelected:!0},{id:`dockerCompose`,group:`deploy`,label:`Docker Compose`,hint:`Infra local com containers.`,templates:Z,defaultSelected:!0},{id:`dockerignore`,group:`deploy`,label:`Dockerignore`,hint:`Exclui do contexto de build tudo que a imagem nao usa.`,templates:Z,defaultSelected:!0},{id:`railway`,group:`deploy`,label:`Railway`,hint:`railway.json do backend, com healthcheck e watch patterns.`,templates:wa,defaultSelected:!1,requires:[`dockerfile`]},{id:`vercel`,group:`deploy`,label:`Vercel`,hint:`vercel.json da app web.`,templates:[`monolith`,`web`],defaultSelected:!1},{id:`telemetry`,group:`pattern`,label:`Telemetry`,hint:`Logs JSON, tracing e error tracking com franchising/telemetry.`,templates:wa,defaultSelected:!1},{id:`betterAuth`,group:`auth`,label:`Better Auth`,hint:`Auth pronta com adapter do ORM escolhido.`,templates:Z,defaultSelected:!1}],Ea=Ta.map(e=>e.id),Da=Ta;function Oa(e){return Da.find(t=>t.id===e)}function ka(e){return Da.filter(t=>t.templates.includes(e))}function Aa(e){return Ea.includes(e)}function ja(e){return ka(e).filter(e=>e.defaultSelected).map(e=>e.id).filter(Aa)}function Ma(e){let t=[...e];for(;t.length>0;){let n=t.pop();if(n)for(let r of Oa(n)?.requires??[])Aa(r)&&!e.has(r)&&(e.add(r),t.push(r))}return e}function Na(e){for(let t of[...e])for(let n of Oa(t)?.conflicts??[])Aa(n)&&e.delete(n);return e}function Pa(e){let t=e.features&&e.features.length>0?e.features:e.fullSetup?ja(e.templateId):[];return Na(Ma(new Set(t.filter(Aa))))}function Fa(e,t){return ja(t).every(t=>e.has(t))}function Ia(e){return Object.fromEntries(Ta.map(t=>[t.id,e.has(t.id)]))}function La(e,t){return Ia(Pa({templateId:`monolith`,fullSetup:e,features:t}))}const Ra=[[`lint`,`Lint`,`lint`],[`typecheck`,`Typecheck`,`typecheck`],[`test`,`Test`,`test`],[`build`,`Build`,`build`]];function za(e,t){return e===`pnpm`?` - name: Setup pnpm
|
|
793
|
+
uses: pnpm/action-setup@v4
|
|
794
|
+
|
|
795
|
+
- name: Setup Node
|
|
796
|
+
uses: actions/setup-node@v4
|
|
797
|
+
with:
|
|
798
|
+
node-version: 22
|
|
799
|
+
cache: pnpm
|
|
800
|
+
|
|
801
|
+
- name: Install dependencies
|
|
802
|
+
run: pnpm install --frozen-lockfile`:` - name: Setup Bun
|
|
803
|
+
uses: oven-sh/setup-bun@v2
|
|
804
|
+
with:
|
|
805
|
+
bun-version: ${t===`bun`?Xn:`1.3.12`}
|
|
806
|
+
|
|
807
|
+
- name: Cache Bun packages
|
|
808
|
+
uses: actions/cache@v4
|
|
809
|
+
with:
|
|
810
|
+
path: ~/.bun/install/cache
|
|
811
|
+
key: bun-\${{ runner.os }}-\${{ hashFiles('bun.lock') }}
|
|
812
|
+
restore-keys: bun-\${{ runner.os }}-
|
|
813
|
+
|
|
814
|
+
- name: Install dependencies
|
|
815
|
+
run: bun install --frozen-lockfile`}function Ba(e,t){let n=za(e,t);return`name: Quality
|
|
514
816
|
|
|
515
817
|
on:
|
|
516
818
|
push:
|
|
@@ -525,55 +827,30 @@ permissions:
|
|
|
525
827
|
contents: read
|
|
526
828
|
|
|
527
829
|
jobs:
|
|
528
|
-
|
|
529
|
-
name:
|
|
830
|
+
${Ra.map(([t,r,i])=>` ${t}:
|
|
831
|
+
name: ${r}
|
|
530
832
|
runs-on: ubuntu-latest
|
|
833
|
+
timeout-minutes: 15
|
|
531
834
|
steps:
|
|
532
835
|
- name: Checkout
|
|
533
836
|
uses: actions/checkout@v4
|
|
534
837
|
|
|
535
|
-
${
|
|
536
|
-
uses: pnpm/action-setup@v4
|
|
838
|
+
${n}
|
|
537
839
|
|
|
538
|
-
- name:
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
- name: Test
|
|
554
|
-
run: pnpm test
|
|
555
|
-
|
|
556
|
-
- name: Build
|
|
557
|
-
run: pnpm build`:` - name: Setup Bun
|
|
558
|
-
uses: oven-sh/setup-bun@v2
|
|
559
|
-
with:
|
|
560
|
-
bun-version: ${t===`bun`?Kn:`1.3.12`}
|
|
561
|
-
|
|
562
|
-
- name: Install dependencies
|
|
563
|
-
run: bun install --frozen-lockfile
|
|
564
|
-
|
|
565
|
-
- name: Lint
|
|
566
|
-
run: bun run lint
|
|
567
|
-
|
|
568
|
-
- name: Typecheck
|
|
569
|
-
run: bun run typecheck
|
|
570
|
-
|
|
571
|
-
- name: Test
|
|
572
|
-
run: bun run test
|
|
573
|
-
|
|
574
|
-
- name: Build
|
|
575
|
-
run: bun run build`}
|
|
576
|
-
`}function Xi(){return`name: CodeQL
|
|
840
|
+
- name: ${r}
|
|
841
|
+
run: ${e} run ${i}
|
|
842
|
+
`).join(`
|
|
843
|
+
`)}
|
|
844
|
+
quality:
|
|
845
|
+
name: Quality
|
|
846
|
+
needs: [${Ra.map(([e])=>e).join(`, `)}]
|
|
847
|
+
if: always()
|
|
848
|
+
runs-on: ubuntu-latest
|
|
849
|
+
steps:
|
|
850
|
+
- name: Check results
|
|
851
|
+
if: contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled')
|
|
852
|
+
run: exit 1
|
|
853
|
+
`}function Va(){return`name: CodeQL
|
|
577
854
|
|
|
578
855
|
on:
|
|
579
856
|
push:
|
|
@@ -604,7 +881,7 @@ jobs:
|
|
|
604
881
|
|
|
605
882
|
- name: Analyze
|
|
606
883
|
uses: github/codeql-action/analyze@v3
|
|
607
|
-
`}function
|
|
884
|
+
`}function Ha(){return`name: Dependency Review
|
|
608
885
|
|
|
609
886
|
on:
|
|
610
887
|
pull_request:
|
|
@@ -623,9 +900,9 @@ jobs:
|
|
|
623
900
|
|
|
624
901
|
- name: Dependency review
|
|
625
902
|
uses: actions/dependency-review-action@v4
|
|
626
|
-
`}function
|
|
903
|
+
`}function Ua(e){return[{path:`.github/CODEOWNERS`,content:`# Default reviewers for all changes in this repository.
|
|
627
904
|
* @almeidarock @wilsonguimaraesrock
|
|
628
|
-
`},{path:`.github/dependabot.yml`,content:`version: 2
|
|
905
|
+
`},{path:`.github/PULL_REQUEST_TEMPLATE.md`,content:Jn(`github/PULL_REQUEST_TEMPLATE.md`)},{path:`.github/dependabot.yml`,content:`version: 2
|
|
629
906
|
updates:
|
|
630
907
|
- package-ecosystem: npm
|
|
631
908
|
directory: /
|
|
@@ -656,7 +933,7 @@ updates:
|
|
|
656
933
|
routine-updates:
|
|
657
934
|
applies-to: version-updates
|
|
658
935
|
update-types: [minor, patch]
|
|
659
|
-
`},...e.workflows.includes(`quality`)?[{path:`.github/workflows/quality.yml`,content:
|
|
936
|
+
`},...e.workflows.includes(`quality`)?[{path:`.github/workflows/quality.yml`,content:Ba(e.packageManager,e.runtime??`node`)}]:[],...e.workflows.includes(`codeql`)?[{path:`.github/workflows/codeql.yml`,content:Va()}]:[],...e.workflows.includes(`dependencyReview`)?[{path:`.github/workflows/dependency-review.yml`,content:Ha()}]:[]]}function Wa(){return`import { Global, Module } from '@nestjs/common';
|
|
660
937
|
import { CacheService } from './cache.service';
|
|
661
938
|
|
|
662
939
|
@Global()
|
|
@@ -665,7 +942,7 @@ import { CacheService } from './cache.service';
|
|
|
665
942
|
exports: [CacheService],
|
|
666
943
|
})
|
|
667
944
|
export class CacheModule {}
|
|
668
|
-
`}function
|
|
945
|
+
`}function Ga(){return`import { Injectable, type OnModuleDestroy } from '@nestjs/common';
|
|
669
946
|
import Redis from 'ioredis';
|
|
670
947
|
import { env } from '../../env';
|
|
671
948
|
|
|
@@ -701,7 +978,7 @@ export class CacheService implements OnModuleDestroy {
|
|
|
701
978
|
await this.client.quit();
|
|
702
979
|
}
|
|
703
980
|
}
|
|
704
|
-
`}function
|
|
981
|
+
`}function Ka(){return`import { Global, Module } from '@nestjs/common';
|
|
705
982
|
import { DatabaseService } from './database.service';
|
|
706
983
|
|
|
707
984
|
@Global()
|
|
@@ -710,7 +987,7 @@ import { DatabaseService } from './database.service';
|
|
|
710
987
|
exports: [DatabaseService],
|
|
711
988
|
})
|
|
712
989
|
export class DatabaseModule {}
|
|
713
|
-
`}function
|
|
990
|
+
`}function qa(){return`import { Injectable, type OnModuleDestroy } from '@nestjs/common';
|
|
714
991
|
import { PrismaClient } from '@prisma/client';
|
|
715
992
|
import { env } from '../../env';
|
|
716
993
|
|
|
@@ -730,6 +1007,7 @@ export class DatabaseService implements OnModuleDestroy {
|
|
|
730
1007
|
|
|
731
1008
|
async connect() {
|
|
732
1009
|
await this.prisma.$connect();
|
|
1010
|
+
|
|
733
1011
|
return this.prisma;
|
|
734
1012
|
}
|
|
735
1013
|
|
|
@@ -739,6 +1017,7 @@ export class DatabaseService implements OnModuleDestroy {
|
|
|
739
1017
|
|
|
740
1018
|
async ping() {
|
|
741
1019
|
await this.prisma.$queryRaw\`SELECT 1\`;
|
|
1020
|
+
|
|
742
1021
|
return 'up';
|
|
743
1022
|
}
|
|
744
1023
|
|
|
@@ -746,7 +1025,7 @@ export class DatabaseService implements OnModuleDestroy {
|
|
|
746
1025
|
await this.prisma.$disconnect();
|
|
747
1026
|
}
|
|
748
1027
|
}
|
|
749
|
-
`}function
|
|
1028
|
+
`}function Ja(){return`import { Injectable, type OnModuleDestroy } from '@nestjs/common';
|
|
750
1029
|
import postgres from 'postgres';
|
|
751
1030
|
import { drizzle } from 'drizzle-orm/postgres-js';
|
|
752
1031
|
import { env } from '../../env';
|
|
@@ -758,10 +1037,11 @@ export class DatabaseService implements OnModuleDestroy {
|
|
|
758
1037
|
max: 10,
|
|
759
1038
|
});
|
|
760
1039
|
|
|
761
|
-
readonly client = drizzle(this.connection, { schema });
|
|
1040
|
+
readonly client = drizzle(this.connection, { schema, casing: 'snake_case' });
|
|
762
1041
|
|
|
763
1042
|
async connect() {
|
|
764
1043
|
await this.connection\`select 1\`;
|
|
1044
|
+
|
|
765
1045
|
return this.client;
|
|
766
1046
|
}
|
|
767
1047
|
|
|
@@ -771,6 +1051,7 @@ export class DatabaseService implements OnModuleDestroy {
|
|
|
771
1051
|
|
|
772
1052
|
async ping() {
|
|
773
1053
|
await this.connection\`select 1\`;
|
|
1054
|
+
|
|
774
1055
|
return 'up';
|
|
775
1056
|
}
|
|
776
1057
|
|
|
@@ -778,15 +1059,7 @@ export class DatabaseService implements OnModuleDestroy {
|
|
|
778
1059
|
await this.connection.end();
|
|
779
1060
|
}
|
|
780
1061
|
}
|
|
781
|
-
`}function
|
|
782
|
-
BETTERSTACK_ERRORS_DSN: str({ default: '' }),
|
|
783
|
-
`:` POSTHOG_API_KEY: str({ default: '' }),
|
|
784
|
-
POSTHOG_HOST: str({ default: 'https://us.i.posthog.com' }),
|
|
785
|
-
`}function aa(e){return{...Jr,...Yr,...Xr[e]}}function oa(e){return e===`betterstack`?`BETTERSTACK_OTLP_ENDPOINT=""
|
|
786
|
-
BETTERSTACK_ERRORS_DSN=""
|
|
787
|
-
`:`POSTHOG_API_KEY=""
|
|
788
|
-
POSTHOG_HOST="https://us.i.posthog.com"
|
|
789
|
-
`}function sa(e,t,n,r,i){return`import 'dotenv/config';
|
|
1062
|
+
`}function Ya(e,t,n,r,i){return`import 'dotenv/config';
|
|
790
1063
|
import { bool, cleanEnv, num, str } from 'envalid';
|
|
791
1064
|
|
|
792
1065
|
export const env = cleanEnv(process.env, {
|
|
@@ -797,14 +1070,13 @@ export const env = cleanEnv(process.env, {
|
|
|
797
1070
|
${e.telemetry?` OTEL_SERVICE_NAME: str({ default: '${r}' }),
|
|
798
1071
|
OTEL_SERVICE_VERSION: str({ default: 'local' }),
|
|
799
1072
|
LOG_LEVEL: str({ default: 'info' }),
|
|
800
|
-
|
|
801
|
-
TELEMETRY_TRACING_ENABLED: bool({ default: true }),
|
|
1073
|
+
${Mr} TELEMETRY_TRACING_ENABLED: bool({ default: true }),
|
|
802
1074
|
TELEMETRY_METRICS_ENABLED: bool({ default: true }),
|
|
803
1075
|
TELEMETRY_LOGS_ENABLED: bool({ default: true }),
|
|
804
1076
|
TELEMETRY_ERRORS_ENABLED: bool({ default: true }),
|
|
805
1077
|
TELEMETRY_HTTP_SUCCESS_LOGS_ENABLED: bool({ default: false }),
|
|
806
1078
|
TELEMETRY_HTTP_SLOW_REQUEST_MS: num({ default: 1000 }),
|
|
807
|
-
${
|
|
1079
|
+
${jr(i)}`:``} MESSAGING_API_KEY: str({ default: '' }),
|
|
808
1080
|
MESSAGING_FROM: str({ default: 'nao-responda@rockfeller.com.br' }),
|
|
809
1081
|
DATABASE_URL: str({
|
|
810
1082
|
desc: 'PostgreSQL connection string',
|
|
@@ -821,35 +1093,101 @@ ${e.betterAuth?` BETTER_AUTH_SECRET: str({
|
|
|
821
1093
|
BETTER_AUTH_URL: str({
|
|
822
1094
|
desc: 'Better Auth base URL',
|
|
823
1095
|
}),
|
|
824
|
-
${
|
|
1096
|
+
${ea(t,n)}`:``}
|
|
825
1097
|
});
|
|
826
|
-
`}function
|
|
1098
|
+
`}function Xa(e,t,n,r,i){return`NODE_ENV="development"
|
|
827
1099
|
PORT=3001
|
|
828
1100
|
${e.telemetry?`OTEL_SERVICE_NAME="${r}"
|
|
829
1101
|
OTEL_SERVICE_VERSION="local"
|
|
830
1102
|
LOG_LEVEL="info"
|
|
831
1103
|
TELEMETRY_HTTP_SUCCESS_LOGS_ENABLED="false"
|
|
832
1104
|
TELEMETRY_HTTP_SLOW_REQUEST_MS="1000"
|
|
833
|
-
${
|
|
1105
|
+
${Pr(i)}`:``}DATABASE_URL="postgresql://docker:docker@localhost:7000/rock"
|
|
834
1106
|
REDIS_PASSWORD="redis_password"
|
|
835
1107
|
REDIS_URL="redis://default:redis_password@localhost:6379"
|
|
836
1108
|
${e.betterAuth?`BETTER_AUTH_SECRET="change-this-secret-with-at-least-32-characters"
|
|
837
1109
|
BETTER_AUTH_URL="http://localhost:3001"
|
|
838
1110
|
CLIENT_ORIGIN="http://localhost:3000"
|
|
839
|
-
${
|
|
840
|
-
`}function
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
1111
|
+
${ta(t,n)}`:``}
|
|
1112
|
+
`}function Za(e,t,n,r,i,a,o=!1,s=`posthog`,c=`node`){let l=`prisma/schema.prisma`,u=r===`prisma`?`prisma generate --schema ${l} && nest build`:`nest build`,d=r===`prisma`?`prisma generate --schema ${l} && tsc-watch --project tsconfig.json --onSuccess "node dist/main.js"`:`tsc-watch --project tsconfig.json --onSuccess "node dist/main.js"`,f={build:u,dev:d,start:`nest start`,"start:dev":d,"start:prod":`node dist/main`,test:`node --test`,typecheck:`tsc --noEmit -p tsconfig.json`,...r===`prisma`?{postinstall:`prisma generate --schema ${l}`}:{},lint:n.ultracite?`ultracite check`:`tsc --noEmit -p tsconfig.json`,check:n.ultracite?`ultracite check && tsc --noEmit -p tsconfig.json && node --test`:`tsc --noEmit -p tsconfig.json && node --test`,"db:generate":r===`prisma`?`prisma generate --schema ${l}`:`drizzle-kit generate`,"db:migrate":r===`prisma`?`prisma migrate dev --schema ${l}`:`drizzle-kit migrate`,"db:studio":r===`prisma`?`prisma studio --schema ${l}`:`drizzle-kit studio`,...n.betterAuth&&r===`prisma`?{"auth:generate":t===`pnpm`?`pnpm exec auth generate`:`bunx auth generate`}:{}};return n.ultracite&&(f[`lint:fix`]=`ultracite fix`,f.format=`ultracite fix`),c===`bun`&&Object.assign(f,$n(r===`prisma`?{predev:`prisma generate --schema ${l}`}:{}),{check:er(f.check??``)}),n.lefthook&&(f.prepare=`lefthook install`),V({name:e,description:`Projeto backend NestJS gerado pelo rockcli`,packageManager:t,runtime:c,type:ga(t).esm?`module`:void 0,sideEffects:!1,keywords:[`rockcli`,`backend`,`nestjs`,r],scripts:f,dependencies:{"@fastify/static":`^8.3.0`,"@nestjs/common":`^11.1.17`,"@nestjs/core":`^11.1.17`,"@nestjs/platform-fastify":`^11.1.17`,"@nestjs/swagger":`^11.2.6`,...Er,...n.telemetry?Nr(s):{},"@scalar/fastify-api-reference":`^1.38.0`,"class-transformer":`^0.5.1`,"class-validator":`^0.14.2`,dotenv:`^16.6.1`,envalid:`^8.1.0`,"reflect-metadata":`^0.2.2`,ioredis:`^5.7.0`,rxjs:`^7.8.2`,...n.betterAuth?{"better-auth":`^1.6.20`,zod:`^4.1.5`,...Ji(a,`^1.6.20`),...i?{"@thallesp/nestjs-better-auth":`^2.7.0`}:{}}:{},...r===`prisma`?{"@prisma/client":`^6.15.0`,...n.betterAuth?{"@better-auth/prisma-adapter":`^1.6.20`}:{}}:{"drizzle-orm":`^0.44.4`,postgres:`^3.4.7`,...n.betterAuth?{"@better-auth/drizzle-adapter":`^1.6.20`}:{}}},devDependencies:{...n.betterAuth&&r===`prisma`?{auth:`^1.6.20`}:{},"@nestjs/cli":`^11.0.17`,"@nestjs/schematics":`^11.0.10`,"@swc/cli":`^0.7.8`,"@swc/core":`^1.13.3`,"@types/node":`^24.0.15`,"tsc-watch":`^6.2.1`,typescript:`^5.9.3`,...r===`prisma`?{prisma:`^6.15.0`}:{"drizzle-kit":`^0.31.4`},...n.ultracite?{...Ca()}:{},...n.lefthook?{lefthook:`^1.11.12`}:{},...n.commitlint?{"@commitlint/cli":`^20.1.0`,"@commitlint/config-conventional":`^20.0.0`}:{}}})}const Qa={id:`api`,label:`api`,description:`Projeto backend isolado em NestJS`,postCreateSteps(e){return Yi(e.authPlugins)},createContext(e){return{hosting:e.hosting,projectName:e.name,projectSlug:Yn(e.name),packageManager:e.packageManager,runtime:e.runtime??`node`,databaseOrm:na(e.databaseOrm),webBases:[],authProviders:e.authProviders??[],authPlugins:e.authPlugins??[],telemetryAdapter:e.telemetryAdapter??`posthog`,workers:e.workers??[],messaging:e.messaging??!1,implementAuthModule:e.implementAuthModule??!1,workflows:e.workflows??[`quality`,`codeql`,`dependencyReview`],features:La(e.fullSetup,e.setupFeatures)}},files(e){let t=na(e.databaseOrm),n=Ua({packageManager:e.packageManager,runtime:e.runtime,workflows:e.workflows});return ba([{path:`package.json`,content:Za(e.projectSlug,e.packageManager,e.features,t,e.implementAuthModule,e.authPlugins,e.messaging,e.telemetryAdapter,e.runtime)},{path:`nest-cli.json`,content:ma()},{path:`tsconfig.json`,content:_a({packageManager:e.packageManager,runtime:e.runtime})},{path:`tsconfig.build.json`,content:ha()},{path:`src/app.module.ts`,content:Li(e.implementAuthModule,e.features.telemetry,e.messaging)},{path:`src/env.ts`,content:Ya(e.features,e.authProviders,e.authPlugins,e.projectSlug,e.telemetryAdapter)},{path:`src/auth.ts`,content:$i(t,e.authProviders,`import { DatabaseService } from './modules/database/database.service';`,e.authPlugins,e.messaging),condition:e=>e.features.betterAuth},{path:`src/modules/auth/auth.module.ts`,content:Ri(`../database/database.service`,e.messaging),condition:e=>e.features.betterAuth&&e.implementAuthModule},{path:`src/modules/auth/auth-session.controller.ts`,content:zi(),condition:e=>e.features.betterAuth&&e.implementAuthModule},{path:`src/modules/cache/cache.module.ts`,content:Wa()},{path:`src/modules/cache/cache.service.ts`,content:Ga()},{path:`src/modules/database/database.module.ts`,content:Ka()},{path:`src/modules/database/database.service.ts`,content:t===`prisma`?qa():Ja()},...t===`drizzle`?pa({schemaPath:`src/modules/database/schema.ts`,tablesDir:`src/tables`,schemaToTables:`../../tables`,betterAuth:e.features.betterAuth,authPlugins:e.authPlugins,webhooks:!1}):[],...ya({prefix:``,projectSlug:e.projectSlug,messaging:e.messaging,authModule:e.implementAuthModule,inlineAuth:e.features.betterAuth&&!e.implementAuthModule,projectName:e.projectName,telemetry:e.features.telemetry,telemetryAdapter:e.telemetryAdapter}),{path:`prisma/schema.prisma`,content:ra(),condition:()=>t===`prisma`},{path:`prisma.config.ts`,content:ia(),condition:()=>t===`prisma`},{path:`drizzle.config.ts`,content:aa({envImport:`./src/env`,schemaPath:`./src/modules/database/schema.ts`}),condition:()=>t===`drizzle`},{path:`.env`,content:Xa(e.features,e.authProviders,e.authPlugins,e.projectSlug,e.telemetryAdapter)},{path:`.env.example`,content:Xa(e.features,e.authProviders,e.authPlugins,e.projectSlug,e.telemetryAdapter)},{path:`docker-compose.yml`,content:ar(),condition:e=>e.features.dockerCompose},{path:`.gitignore`,content:rr()},..._r({railway:e.features.railway,vercel:!1,webPrefix:``,railwayOptions:{prefix:``,watchedPackages:[],packageManager:e.packageManager,healthcheckPath:`/v1/health`,preDeployCommand:t===`prisma`?`prisma migrate deploy`:`drizzle-kit migrate`},vercelOptions:{packageManager:e.packageManager,monorepo:!1}}),...Sa({hasWeb:!1,hasApi:!0,editorconfig:e.features.editorconfig,lefthook:e.features.lefthook,ultracite:e.features.ultracite,commitlint:e.features.commitlint,dockerignore:e.features.dockerignore,packageManager:e.packageManager}),{path:`commitlint.config.ts`,content:ir(),condition:e=>e.features.commitlint},{path:`Dockerfile`,content:``,condition:e=>e.features.dockerfile},...n],!!e.messaging)}};function $a(e){let t=/* @__PURE__ */ new Set([...e.authProviders,...e.authPlugins]);return e.betterAuth&&t.add(`betterAuth`),e.authProviders.some(e=>e!==`emailAndPassword`)&&t.add(`hasSocial`),{has:e=>t.has(e),tokens:{__ROCK_PROJECT_NAME__:e.projectName,__ROCK_AUTH_CLIENT_IMPORTS__:Gi(e.authPlugins),__ROCK_AUTH_CLIENT_PLUGINS__:qi(e.authPlugins)}}}function eo(e){let t=$a(e);return U({dir:`web`,prefix:e.prefix,entries:[{source:`postcss.config.mjs`},{source:`src/app/layout.tsx`},{source:`src/app/globals.css`},{source:`src/app/page.tsx`},{source:`src/components/shell/providers.tsx`},{source:`src/shared/api/client.ts`},{source:`src/types/api.ts`},{source:`src/app/(auth)/login/page.tsx`,condition:()=>e.betterAuth},{source:`src/app/(app)/layout.tsx`,condition:()=>e.betterAuth},{source:`src/app/(app)/dashboard/page.tsx`,condition:()=>e.betterAuth},{source:`src/components/overview/overview-panel.tsx`,condition:()=>e.betterAuth},{source:`src/components/shell/app-shell.tsx`,condition:()=>e.betterAuth},{source:`src/shared/auth/client.ts`,condition:()=>e.betterAuth},{source:`src/shared/auth/server.ts`,condition:()=>e.betterAuth}]},t)}function to(e){return{...Er,...Ar,...e.betterAuth?{"better-auth":`^1.6.20`,...Ji(e.authPlugins??[],`^1.6.20`,`client`)}:{}}}function no(){return{"@tailwindcss/postcss":`^4.1.11`,tailwindcss:`^4.1.11`}}const ro=`^0.44.4`;function io(){return`
|
|
1113
|
+
/// Destinos de webhook, um por URL cadastrada pelo dono.
|
|
1114
|
+
model WebhookEndpoint {
|
|
1115
|
+
id String @id @default(uuid()) @db.Uuid
|
|
1116
|
+
ownerId String @map("owner_id")
|
|
1117
|
+
url String
|
|
1118
|
+
/// Segredo whsec_ cifrado com AES-256-GCM (WEBHOOK_SECRETS_KEY).
|
|
1119
|
+
secret String
|
|
1120
|
+
eventTypes String[] @map("event_types")
|
|
1121
|
+
enabled Boolean @default(true)
|
|
1122
|
+
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
|
|
1123
|
+
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz
|
|
1124
|
+
deliveries WebhookDelivery[]
|
|
1125
|
+
|
|
1126
|
+
@@index([ownerId])
|
|
1127
|
+
@@map("webhook_endpoints")
|
|
1128
|
+
}
|
|
844
1129
|
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
1130
|
+
/// Eventos esperando entrega; a API grava na transacao do negocio.
|
|
1131
|
+
model WebhookOutbox {
|
|
1132
|
+
id String @id @default(uuid()) @db.Uuid
|
|
1133
|
+
ownerId String @map("owner_id")
|
|
1134
|
+
eventType String @map("event_type")
|
|
1135
|
+
payload Json
|
|
1136
|
+
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
|
|
1137
|
+
dispatchedAt DateTime? @map("dispatched_at") @db.Timestamptz
|
|
1138
|
+
|
|
1139
|
+
@@index([dispatchedAt, createdAt])
|
|
1140
|
+
@@map("webhook_outbox")
|
|
1141
|
+
}
|
|
1142
|
+
|
|
1143
|
+
/// Cada tentativa de entrega, com o status que o receptor respondeu.
|
|
1144
|
+
model WebhookDelivery {
|
|
1145
|
+
id String @id @default(uuid()) @db.Uuid
|
|
1146
|
+
endpointId String @map("endpoint_id") @db.Uuid
|
|
1147
|
+
endpoint WebhookEndpoint @relation(fields: [endpointId], references: [id], onDelete: Cascade)
|
|
1148
|
+
messageId String @map("message_id") @db.Uuid
|
|
1149
|
+
eventType String @map("event_type")
|
|
1150
|
+
attempt Int
|
|
1151
|
+
status String
|
|
1152
|
+
responseStatus Int? @map("response_status")
|
|
1153
|
+
error String?
|
|
1154
|
+
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
|
|
1155
|
+
|
|
1156
|
+
@@index([endpointId, createdAt])
|
|
1157
|
+
@@map("webhook_deliveries")
|
|
1158
|
+
}
|
|
1159
|
+
`}function ao(e){return`import type { DatabaseService } from '../../database.service';
|
|
1160
|
+
|
|
1161
|
+
/**
|
|
1162
|
+
* Transacao aberta pelo cliente do banco.
|
|
1163
|
+
*
|
|
1164
|
+
* @remarks
|
|
1165
|
+
* Quem publica um webhook passa a transacao da propria mudanca: o evento so
|
|
1166
|
+
* existe se a mudanca foi gravada.
|
|
1167
|
+
*/
|
|
1168
|
+
export type DatabaseTransaction = Parameters<
|
|
1169
|
+
Parameters<DatabaseService['client']['${e===`prisma`?`$transaction`:`transaction`}']>[0]
|
|
1170
|
+
>[0];
|
|
1171
|
+
`}function oo(e,t){let n=JSON.parse(e);return t(n),`${JSON.stringify(n,null,` `)}\n`}function so(e,t){e.dependencies=Object.fromEntries(Object.entries({...t,...e.dependencies}).sort(([e],[t])=>e.localeCompare(t)))}function co(e,t){let n=oe(32).toString(`base64`),r={has:e=>e===t.databaseOrm||e===`routes`&&t.routes||e===`telemetry`&&t.telemetry,tokens:{__ROCK_SCOPE__:t.scope}},i=t.databaseOrm===`drizzle`,a=U({dir:`webhooks/api`,prefix:`apps/api`,entries:[{source:`src/modules/webhooks/module.ts`},{source:`src/modules/webhooks/service.ts`},{source:`src/modules/webhooks/repository.ts`},{source:`src/modules/webhooks/controller.ts`,condition:()=>t.routes},{source:`src/modules/webhooks/dto/create-endpoint.dto.ts`,condition:()=>t.routes},{source:`src/modules/webhooks/dto/endpoint.dto.ts`,condition:()=>t.routes},{source:`src/types/webhooks/endpoint.ts`}]},r),o={"apps/api/src/app.module.ts":e=>e.replace(/^(import \{ HealthModule \} from .*;)$/m,`$1
|
|
1172
|
+
import { WebhooksModule } from './modules/webhooks/module';`).replace(/HealthModule(, AppAuthModule)?\]/,`HealthModule$1, WebhooksModule]`),"apps/api/src/shared/http/errors.ts":e=>e.replace(/\n\}\);\n$/,`
|
|
1173
|
+
WebhookEndpointNotFound: {
|
|
1174
|
+
message: 'Webhook endpoint not found.',
|
|
1175
|
+
status: 404,
|
|
1176
|
+
},
|
|
1177
|
+
WebhookUrlNotAllowed: {
|
|
1178
|
+
message: 'The webhook URL must be public HTTPS.',
|
|
1179
|
+
status: 400,
|
|
1180
|
+
},
|
|
1181
|
+
});
|
|
1182
|
+
`),"apps/api/src/env.ts":e=>e.replace(/\n\}\);\n$/,`
|
|
1183
|
+
WEBHOOK_SECRETS_KEY: str({
|
|
1184
|
+
desc: 'Chave AES-256 dos segredos de webhook (openssl rand -base64 32).',
|
|
1185
|
+
}),
|
|
1186
|
+
});
|
|
1187
|
+
`),"apps/api/.env":e=>`${e.trimEnd()}\nWEBHOOK_SECRETS_KEY="${n}"\n`,"apps/api/.env.example":e=>`${e.trimEnd()}\nWEBHOOK_SECRETS_KEY=""\n`,"apps/workers/webhooks/.env":e=>e.replace(/^WEBHOOK_SECRETS_KEY=.*$/m,`WEBHOOK_SECRETS_KEY="${n}"`),"apps/api/package.json":e=>oo(e,e=>so(e,{[`${t.scope}/webhooks`]:`workspace:*`,...i?{"drizzle-orm":ro}:{}})),"packages/database/src/index.ts":e=>`${e}${i?`export * from './schema';
|
|
1188
|
+
`:``}export type { DatabaseTransaction } from './types/database/transaction';\n`,"packages/database/prisma/schema.prisma":e=>`${e}${io()}`};return[...e.map(e=>{let t=o[e.path];return!t||e.content===void 0?e:{...e,content:t(e.content)}}),...a,{path:`packages/database/src/types/database/transaction.ts`,content:ao(t.databaseOrm)}]}function lo(){return[{source:`src/env.ts`},{source:`src/modules/queue/module.ts`},{source:`src/modules/queue/processor.ts`},{source:`src/modules/queue/dispatcher.ts`},{source:`src/modules/queue/repository.ts`},{source:`src/shared/http/deliver.ts`},{source:`src/types/webhooks/dispatch.ts`}]}function uo(e){return e.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(``)}function fo(e){return e.split(/[^a-zA-Z0-9]+/).filter(Boolean).join(`_`).toUpperCase()}function po(e,t){return`${e}/worker-${t.name}`}function mo(e){let t=fo(e.worker.name);return{has:t=>t===`telemetry`&&!!e.telemetry||t===(e.databaseOrm??`drizzle`),tokens:{__ROCK_SCOPE__:e.scope,__ROCK_PROJECT_SLUG__:e.projectSlug,__ROCK_WORKER_NAME__:e.worker.name,__ROCK_WORKER_QUEUE__:e.worker.queue,__ROCK_WORKER_CLASS__:uo(e.worker.name),__ROCK_WORKER_QUEUE_CONST__:`${t}_QUEUE_NAME`,__ROCK_WORKER_CONCURRENCY_ENV__:`${t}_CONCURRENCY`}}}function ho(e){let t=e.worker.kind===`messaging`,n=e.worker.kind===`webhooks`;return V({name:po(e.scope,e.worker),description:`Worker da fila ${e.worker.queue}`,packageManager:e.packageManager,runtime:e.runtime,scripts:{build:`tsc -p tsconfig.build.json`,...e.runtime===`bun`?{dev:`bun --watch src/main.ts`,start:`bun src/main.ts`}:{dev:`tsc-watch --project tsconfig.json --onSuccess "node dist/main.js"`,start:`node dist/main.js`},lint:`ultracite check`,test:`bun test`,typecheck:`tsc --noEmit -p tsconfig.json`},dependencies:{...Object.fromEntries([...e.packages,...n?[`database`,`webhooks`]:[]].map(t=>[`${e.scope}/${t}`,`workspace:*`])),...n&&(e.databaseOrm??`drizzle`)===`drizzle`?{"drizzle-orm":ro}:{},"@nestjs/common":`^11.1.17`,"@nestjs/core":`^11.1.17`,...t?Er:{},...e.telemetryAdapter?Nr(e.telemetryAdapter):{},bullmq:`^5.63.0`,dotenv:`^16.6.1`,envalid:`^8.1.0`,ioredis:`^5.4.1`,"reflect-metadata":`^0.2.2`,rxjs:`^7.8.2`},devDependencies:{"@types/node":`^24.0.15`,"tsc-watch":`^6.2.1`,typescript:`^5.9.3`}})}function go(e){return H({extends:`../../../tsconfig.base.json`,compilerOptions:{module:`CommonJS`,moduleResolution:`node`,target:`ES2023`,experimentalDecorators:!0,emitDecoratorMetadata:!0,declaration:!1,incremental:!e,rootDir:`./src`,outDir:`./dist`,types:[`node`]},include:[`src/**/*.ts`],exclude:[`node_modules`,`dist`,...e?[`test`]:[]]})}function _o(e){let t=e.telemetry?e.telemetryAdapter??`posthog`:void 0;return e.workers.flatMap(n=>{let r=`apps/workers/${n.name}`,i=mo({scope:e.scope,projectSlug:e.projectSlug,worker:n,telemetry:!!t,databaseOrm:e.databaseOrm}),a=n.kind===`messaging`,o=n.kind===`webhooks`,s=[`QUEUE_REDIS_URL="redis://default:redis_password@localhost:6379"`,...a?[`MESSAGING_API_KEY=""`,`MESSAGING_FROM=""`]:[],...o?[`DATABASE_URL="postgresql://docker:docker@localhost:7000/rock"`,`WEBHOOK_SECRETS_KEY=""`,`WEBHOOKS_DISPATCH_INTERVAL_MS="1000"`,`WEBHOOKS_DISPATCH_BATCH_SIZE="100"`,`WEBHOOKS_TIMEOUT_MS="10000"`]:[],...t?[`OTEL_SERVICE_NAME="${e.projectSlug}-${n.name}"`,`OTEL_SERVICE_VERSION="local"`,`LOG_LEVEL="info"`,Pr(t).trimEnd()]:[]].join(`
|
|
1189
|
+
`);return[...U({dir:`worker`,prefix:r,entries:[{source:`src/main.ts`},{source:`src/app.module.ts`},...a||o?[]:[{source:`src/env.ts`},{source:`src/modules/queue/module.ts`},{source:`src/modules/queue/processor.ts`},{source:`src/modules/queue/repository.ts`}],{source:`src/modules/queue/config.ts`},{source:`src/modules/queue/retry.ts`},{source:`test/retry.test.ts.tpl`}]},i),...a?U({dir:`worker-messaging`,prefix:r,entries:[{source:`src/env.ts`},{source:`src/modules/queue/module.ts`},{source:`src/modules/queue/processor.ts`},{source:`src/modules/messaging/service.ts`}]},i):[],...o?U({dir:`webhooks/worker`,prefix:r,entries:lo()},i):[],{path:`${r}/.env`,content:`${s}\n`},{path:`${r}/.env.example`,content:`${s}\n`},{path:`${r}/package.json`,content:ho({scope:e.scope,worker:n,packageManager:e.packageManager,runtime:e.runtime,packages:e.packages,telemetryAdapter:t,databaseOrm:e.databaseOrm})},{path:`${r}/tsconfig.json`,content:go(!1)},{path:`${r}/tsconfig.build.json`,content:go(!0)}]})}function vo(e){return`${e.map(e=>`export const ${fo(e.name)}_QUEUE_NAME = '${e.queue}';`).join(`
|
|
1190
|
+
`)||`export {};`}\n`}function yo(e,t){let[n,r]=U({dir:`worker-messaging`,prefix:``,entries:[{source:`messaging-api-service.ts`,target:`apps/api/src/modules/messaging/service.ts`},{source:`jobs-messaging.ts`,target:`packages/jobs/src/types/queue/messaging.ts`}]},{has:()=>!1,tokens:{__ROCK_SCOPE__:t.scope}});return[...e.map(e=>{if(e.content===void 0)return e;if(e.path===`apps/api/src/modules/messaging/service.ts`)return{...e,content:n?.content};if(e.path===`packages/jobs/src/index.ts`)return{...e,content:`${e.content}export type { SendEmailJob } from './types/queue/messaging';\n`};if(e.path===`apps/api/src/env.ts`)return{...e,content:e.content.replace(/^ {2}MESSAGING_(?:API_KEY|FROM):.*\n/gm,``).replace(` REDIS_URL: str({`,` QUEUE_PREFIX: str({ default: '${t.projectSlug}' }),\n REDIS_URL: str({`)};if(e.path===`apps/api/package.json`){let n=JSON.parse(e.content);return n.dependencies=Object.fromEntries(Object.entries({...n.dependencies,[`${t.scope}/jobs`]:`workspace:*`,[`${t.scope}/queue`]:`workspace:*`,bullmq:`^5.63.0`}).sort(([e],[t])=>e.localeCompare(t))),{...e,content:`${JSON.stringify(n,null,` `)}\n`}}return e}),...r?[r]:[]]}function bo(e){let t=e.authPlugins,n={build:`nest build`,dev:`tsc-watch --project tsconfig.json --onSuccess "node dist/main.js"`,start:`nest start`,"start:dev":`tsc-watch --project tsconfig.json --onSuccess "node dist/main.js"`,"start:prod":`node dist/main`,test:`node --test`,typecheck:`tsc --noEmit -p tsconfig.json`,lint:e.features.ultracite?`ultracite check`:`tsc --noEmit -p tsconfig.json`,check:e.features.ultracite?`ultracite check && tsc --noEmit -p tsconfig.json && node --test`:`tsc --noEmit -p tsconfig.json && node --test`,...e.features.betterAuth&&e.databaseOrm===`prisma`?{"auth:generate":e.packageManager===`pnpm`?`pnpm exec auth generate`:`bunx auth generate`}:{}};return e.runtime===`bun`&&Object.assign(n,$n(),{check:er(n.check??``)}),e.features.ultracite&&(n[`lint:fix`]=`ultracite fix`,n.format=`ultracite fix`),V({name:`api`,description:`API NestJS do monorepo Rock`,packageManager:e.packageManager,runtime:e.runtime,type:ga(e.packageManager).esm?`module`:void 0,sideEffects:!1,keywords:[`rockcli`,`api`,`nestjs`],scripts:n,dependencies:{"@fastify/static":`^8.3.0`,"@nestjs/common":`^11.1.17`,"@nestjs/core":`^11.1.17`,"@nestjs/platform-fastify":`^11.1.17`,"@nestjs/swagger":`^11.2.6`,...Er,...e.features.telemetry?Nr(e.telemetryAdapter):{},"@scalar/fastify-api-reference":`^1.38.0`,...e.features.betterAuth?{"better-auth":`^1.6.20`,zod:`^4.1.5`,...Ji(t,`^1.6.20`),...e.implementAuthModule?{"@thallesp/nestjs-better-auth":`^2.7.0`}:{}}:{},"@repo/cache":`workspace:*`,"@repo/database":`workspace:*`,...e.features.telemetry?{"@repo/observability":`workspace:*`}:{},"class-transformer":`^0.5.1`,"class-validator":`^0.14.2`,dotenv:`^16.6.1`,envalid:`^8.1.0`,"reflect-metadata":`^0.2.2`,ioredis:`^5.7.0`,rxjs:`^7.8.2`,...e.features.betterAuth?e.databaseOrm===`prisma`?{"@better-auth/prisma-adapter":`^1.6.20`}:{"@better-auth/drizzle-adapter":`^1.6.20`}:{}},devDependencies:{...e.features.betterAuth&&e.databaseOrm===`prisma`?{auth:`^1.6.20`}:{},"@nestjs/cli":`^11.0.17`,"@nestjs/schematics":`^11.0.10`,"@swc/cli":`^0.7.8`,"@swc/core":`^1.13.3`,"@types/node":`^24.0.15`,"tsc-watch":`^6.2.1`,typescript:`^5.9.3`}})}function xo(e,t,n,r,i){return`import 'dotenv/config';
|
|
853
1191
|
import { bool, cleanEnv, num, str } from 'envalid';
|
|
854
1192
|
|
|
855
1193
|
export const env = cleanEnv(process.env, {
|
|
@@ -860,14 +1198,13 @@ export const env = cleanEnv(process.env, {
|
|
|
860
1198
|
${e.telemetry?` OTEL_SERVICE_NAME: str({ default: '${r}' }),
|
|
861
1199
|
OTEL_SERVICE_VERSION: str({ default: 'local' }),
|
|
862
1200
|
LOG_LEVEL: str({ default: 'info' }),
|
|
863
|
-
|
|
864
|
-
TELEMETRY_TRACING_ENABLED: bool({ default: true }),
|
|
1201
|
+
${Mr} TELEMETRY_TRACING_ENABLED: bool({ default: true }),
|
|
865
1202
|
TELEMETRY_METRICS_ENABLED: bool({ default: true }),
|
|
866
1203
|
TELEMETRY_LOGS_ENABLED: bool({ default: true }),
|
|
867
1204
|
TELEMETRY_ERRORS_ENABLED: bool({ default: true }),
|
|
868
1205
|
TELEMETRY_HTTP_SUCCESS_LOGS_ENABLED: bool({ default: false }),
|
|
869
1206
|
TELEMETRY_HTTP_SLOW_REQUEST_MS: num({ default: 1000 }),
|
|
870
|
-
${
|
|
1207
|
+
${jr(i)}`:``} MESSAGING_API_KEY: str({ default: '' }),
|
|
871
1208
|
MESSAGING_FROM: str({ default: 'nao-responda@rockfeller.com.br' }),
|
|
872
1209
|
DATABASE_URL: str({
|
|
873
1210
|
desc: 'PostgreSQL connection string',
|
|
@@ -884,9 +1221,9 @@ ${e.betterAuth?` BETTER_AUTH_SECRET: str({
|
|
|
884
1221
|
BETTER_AUTH_URL: str({
|
|
885
1222
|
desc: 'Better Auth base URL',
|
|
886
1223
|
}),
|
|
887
|
-
${
|
|
1224
|
+
${ea(t,n)}`:``}
|
|
888
1225
|
});
|
|
889
|
-
`}function
|
|
1226
|
+
`}function So(){return`import { Global, Module } from '@nestjs/common';
|
|
890
1227
|
import { DatabaseService } from './database.service';
|
|
891
1228
|
|
|
892
1229
|
@Global()
|
|
@@ -895,13 +1232,18 @@ import { DatabaseService } from './database.service';
|
|
|
895
1232
|
exports: [DatabaseService],
|
|
896
1233
|
})
|
|
897
1234
|
export class DatabaseModule {}
|
|
898
|
-
`}function
|
|
1235
|
+
`}function Co(){return`import { Injectable, type OnModuleDestroy } from '@nestjs/common';
|
|
899
1236
|
import { DatabaseService as SharedDatabaseService } from '@repo/database';
|
|
900
1237
|
|
|
901
1238
|
@Injectable()
|
|
902
1239
|
export class DatabaseService implements OnModuleDestroy {
|
|
903
1240
|
private readonly database = new SharedDatabaseService();
|
|
904
1241
|
|
|
1242
|
+
/** Cliente do ORM, para o Better Auth e os repositorios que montam a propria consulta. */
|
|
1243
|
+
get client(): SharedDatabaseService['client'] {
|
|
1244
|
+
return this.database.client;
|
|
1245
|
+
}
|
|
1246
|
+
|
|
905
1247
|
async connect(): Promise<void> {
|
|
906
1248
|
await this.database.connect();
|
|
907
1249
|
}
|
|
@@ -918,7 +1260,7 @@ export class DatabaseService implements OnModuleDestroy {
|
|
|
918
1260
|
await this.database.disconnect();
|
|
919
1261
|
}
|
|
920
1262
|
}
|
|
921
|
-
`}function
|
|
1263
|
+
`}function wo(){return`import { Global, Module } from '@nestjs/common';
|
|
922
1264
|
import { CacheService } from './cache.service';
|
|
923
1265
|
|
|
924
1266
|
@Global()
|
|
@@ -927,7 +1269,7 @@ import { CacheService } from './cache.service';
|
|
|
927
1269
|
exports: [CacheService],
|
|
928
1270
|
})
|
|
929
1271
|
export class CacheModule {}
|
|
930
|
-
`}function
|
|
1272
|
+
`}function To(){return`import { Injectable, type OnModuleDestroy } from '@nestjs/common';
|
|
931
1273
|
import { CacheService as SharedCacheService } from '@repo/cache';
|
|
932
1274
|
|
|
933
1275
|
@Injectable()
|
|
@@ -954,18 +1296,8 @@ export class CacheService implements OnModuleDestroy {
|
|
|
954
1296
|
await this.cache.disconnect();
|
|
955
1297
|
}
|
|
956
1298
|
}
|
|
957
|
-
`}function
|
|
958
|
-
|
|
959
|
-
COPY . .
|
|
960
|
-
RUN ${e} install
|
|
961
|
-
|
|
962
|
-
FROM oven/bun:1 AS runner
|
|
963
|
-
WORKDIR /app
|
|
964
|
-
COPY --from=deps /app ./
|
|
965
|
-
EXPOSE 3001
|
|
966
|
-
CMD ${t===`bun`?`["bun", "run", "start:api"]`:`["${e}", "run", "dev:api"]`}
|
|
967
|
-
`}function Pa(){return W({extends:`../../tsconfig.base.json`,compilerOptions:{baseUrl:`.`,paths:{},target:`ES2022`,module:`CommonJS`,moduleResolution:`node`,lib:[`ES2022`],types:[`node`],strict:!0,declaration:!0,declarationMap:!0,sourceMap:!0,outDir:`./dist`,rootDir:`./src`,noEmit:!1},include:[`src/**/*.ts`],exclude:[`dist`,`node_modules`]})}function Fa(e){return U({name:`@repo/cache`,version:`0.0.0`,description:`Camada de cache compartilhada do monorepo Rock`,packageManager:e.packageManager,sideEffects:!1,keywords:[`rockcli`,`cache`,`redis`,`dragonfly`],main:`./dist/index.js`,types:`./src/index.ts`,exports:{".":{types:`./src/index.ts`,default:`./dist/index.js`}},files:[`dist`],scripts:{build:`tsc -p tsconfig.build.json`,lint:e.features.ultracite?`ultracite check`:`tsc --noEmit -p tsconfig.build.json`,test:`echo "No tests configured yet"`,typecheck:`tsc --noEmit -p tsconfig.build.json`},dependencies:{dotenv:`^16.6.1`,envalid:`^8.1.0`,ioredis:`^5.7.0`},devDependencies:{"@types/node":`^24.0.15`,typescript:`^5.9.3`}})}function Ia(){return`export { CacheService } from './cache.service';
|
|
968
|
-
`}function La(){return`import 'dotenv/config';
|
|
1299
|
+
`}function Eo(){return H({extends:`../../tsconfig.base.json`,compilerOptions:{baseUrl:`.`,paths:{},target:`ES2022`,module:`CommonJS`,moduleResolution:`node`,lib:[`ES2022`],types:[`node`],strict:!0,declaration:!0,declarationMap:!0,sourceMap:!0,outDir:`./dist`,rootDir:`./src`,noEmit:!1},include:[`src/**/*.ts`],exclude:[`dist`,`node_modules`]})}function Do(e){return V({name:`@repo/cache`,version:`0.0.0`,description:`Camada de cache compartilhada do monorepo Rock`,packageManager:e.packageManager,sideEffects:!1,keywords:[`rockcli`,`cache`,`redis`,`dragonfly`],main:`./dist/index.js`,types:`./src/index.ts`,exports:{".":{types:`./src/index.ts`,default:`./dist/index.js`}},files:[`dist`],scripts:{build:`tsc -p tsconfig.build.json`,lint:e.features.ultracite?`ultracite check`:`tsc --noEmit -p tsconfig.build.json`,test:`echo "No tests configured yet"`,typecheck:`tsc --noEmit -p tsconfig.build.json`},dependencies:{dotenv:`^16.6.1`,envalid:`^8.1.0`,ioredis:`^5.7.0`},devDependencies:{"@types/node":`^24.0.15`,typescript:`^5.9.3`}})}function Oo(){return`export { CacheService } from './cache.service';
|
|
1300
|
+
`}function ko(){return`import 'dotenv/config';
|
|
969
1301
|
import { cleanEnv, str } from 'envalid';
|
|
970
1302
|
|
|
971
1303
|
export const env = cleanEnv(process.env, {
|
|
@@ -976,7 +1308,7 @@ export const env = cleanEnv(process.env, {
|
|
|
976
1308
|
desc: 'Dragonfly/Redis password',
|
|
977
1309
|
}),
|
|
978
1310
|
});
|
|
979
|
-
`}function
|
|
1311
|
+
`}function Ao(){return`import Redis from 'ioredis';
|
|
980
1312
|
import { env } from './env';
|
|
981
1313
|
|
|
982
1314
|
export class CacheService {
|
|
@@ -989,6 +1321,7 @@ export class CacheService {
|
|
|
989
1321
|
async set(key: string, value: string, ttlInSeconds?: number): Promise<void> {
|
|
990
1322
|
if (ttlInSeconds) {
|
|
991
1323
|
await this.client.setex(key, ttlInSeconds, value);
|
|
1324
|
+
|
|
992
1325
|
return;
|
|
993
1326
|
}
|
|
994
1327
|
|
|
@@ -1001,6 +1334,7 @@ export class CacheService {
|
|
|
1001
1334
|
|
|
1002
1335
|
async ping(): Promise<string> {
|
|
1003
1336
|
const result = await this.client.ping();
|
|
1337
|
+
|
|
1004
1338
|
return result.toLowerCase();
|
|
1005
1339
|
}
|
|
1006
1340
|
|
|
@@ -1008,23 +1342,16 @@ export class CacheService {
|
|
|
1008
1342
|
await this.client.quit();
|
|
1009
1343
|
}
|
|
1010
1344
|
}
|
|
1011
|
-
`}function
|
|
1012
|
-
|
|
1013
|
-
`}function Va(){return`import 'dotenv/config';
|
|
1345
|
+
`}function jo(e){let t=na(e.databaseOrm),n=`./prisma/schema.prisma`;return V({name:`@repo/database`,version:`0.0.0`,description:`Camada de dados compartilhada do monorepo Rock`,packageManager:e.packageManager,sideEffects:!1,keywords:[`rockcli`,`database`,t],main:`./dist/index.js`,types:`./src/index.ts`,exports:{".":{types:`./src/index.ts`,default:`./dist/index.js`},...t===`drizzle`?{"./schema":{types:`./src/tables/index.ts`,default:`./dist/tables/index.js`}}:{}},files:[`dist`],scripts:{build:t===`prisma`?`prisma generate --schema ${n} && tsc -p tsconfig.build.json`:`tsc -p tsconfig.build.json`,lint:e.features.ultracite?`ultracite check`:`tsc --noEmit -p tsconfig.build.json`,test:`echo "No tests configured yet"`,typecheck:`tsc --noEmit -p tsconfig.build.json`,...t===`prisma`?{postinstall:`prisma generate --schema ${n}`}:{},"db:generate":t===`prisma`?`prisma generate --schema ${n}`:`drizzle-kit generate`,"db:migrate":t===`prisma`?`prisma migrate dev --schema ${n}`:`drizzle-kit migrate`,"db:studio":t===`prisma`?`prisma studio --schema ${n}`:`drizzle-kit studio`},dependencies:t===`prisma`?{"@prisma/client":`^6.15.0`,dotenv:`^16.6.1`,envalid:`^8.1.0`}:{"drizzle-orm":`^0.44.4`,dotenv:`^16.6.1`,envalid:`^8.1.0`,postgres:`^3.4.7`},devDependencies:{"@types/node":`^24.0.15`,typescript:`^5.9.3`,...t===`prisma`?{prisma:`^6.15.0`}:{"drizzle-kit":`^0.31.4`}}})}function Mo(){return`export { DatabaseService } from './database.service';
|
|
1346
|
+
`}function No(){return`import 'dotenv/config';
|
|
1014
1347
|
import { cleanEnv, str } from 'envalid';
|
|
1015
1348
|
|
|
1016
1349
|
export const env = cleanEnv(process.env, {
|
|
1017
1350
|
DATABASE_URL: str({
|
|
1018
1351
|
desc: 'PostgreSQL connection string',
|
|
1019
1352
|
}),
|
|
1020
|
-
REDIS_URL: str({
|
|
1021
|
-
desc: 'Dragonfly/Redis connection string',
|
|
1022
|
-
}),
|
|
1023
|
-
REDIS_PASSWORD: str({
|
|
1024
|
-
desc: 'Dragonfly/Redis password',
|
|
1025
|
-
}),
|
|
1026
1353
|
});
|
|
1027
|
-
`}function
|
|
1354
|
+
`}function Po(){return`import { PrismaClient } from '@prisma/client';
|
|
1028
1355
|
import { env } from './env';
|
|
1029
1356
|
|
|
1030
1357
|
export class DatabaseService {
|
|
@@ -1042,6 +1369,7 @@ export class DatabaseService {
|
|
|
1042
1369
|
|
|
1043
1370
|
async connect() {
|
|
1044
1371
|
await this.prisma.$connect();
|
|
1372
|
+
|
|
1045
1373
|
return this.prisma;
|
|
1046
1374
|
}
|
|
1047
1375
|
|
|
@@ -1051,10 +1379,11 @@ export class DatabaseService {
|
|
|
1051
1379
|
|
|
1052
1380
|
async ping() {
|
|
1053
1381
|
await this.prisma.$queryRaw\`SELECT 1\`;
|
|
1382
|
+
|
|
1054
1383
|
return 'up';
|
|
1055
1384
|
}
|
|
1056
1385
|
}
|
|
1057
|
-
`}function
|
|
1386
|
+
`}function Fo(){return`import postgres from 'postgres';
|
|
1058
1387
|
import { drizzle } from 'drizzle-orm/postgres-js';
|
|
1059
1388
|
import { env } from './env';
|
|
1060
1389
|
import * as schema from './schema';
|
|
@@ -1064,10 +1393,11 @@ export class DatabaseService {
|
|
|
1064
1393
|
max: 10,
|
|
1065
1394
|
});
|
|
1066
1395
|
|
|
1067
|
-
readonly client = drizzle(this.connection, { schema });
|
|
1396
|
+
readonly client = drizzle(this.connection, { schema, casing: 'snake_case' });
|
|
1068
1397
|
|
|
1069
1398
|
async connect() {
|
|
1070
1399
|
await this.connection\`select 1\`;
|
|
1400
|
+
|
|
1071
1401
|
return this.client;
|
|
1072
1402
|
}
|
|
1073
1403
|
|
|
@@ -1077,19 +1407,11 @@ export class DatabaseService {
|
|
|
1077
1407
|
|
|
1078
1408
|
async ping() {
|
|
1079
1409
|
await this.connection\`select 1\`;
|
|
1410
|
+
|
|
1080
1411
|
return 'up';
|
|
1081
1412
|
}
|
|
1082
1413
|
}
|
|
1083
|
-
`}function
|
|
1084
|
-
|
|
1085
|
-
export const users = pgTable('users', {
|
|
1086
|
-
id: uuid('id').defaultRandom().primaryKey(),
|
|
1087
|
-
email: text('email').notNull().unique(),
|
|
1088
|
-
createdAt: timestamp('created_at', { withTimezone: true })
|
|
1089
|
-
.defaultNow()
|
|
1090
|
-
.notNull(),
|
|
1091
|
-
});
|
|
1092
|
-
`}function Ga(){return`generator client {
|
|
1414
|
+
`}function Io(){return`generator client {
|
|
1093
1415
|
provider = "prisma-client-js"
|
|
1094
1416
|
}
|
|
1095
1417
|
|
|
@@ -1103,7 +1425,7 @@ model User {
|
|
|
1103
1425
|
email String @unique
|
|
1104
1426
|
createdAt DateTime @default(now())
|
|
1105
1427
|
}
|
|
1106
|
-
`}function
|
|
1428
|
+
`}function Lo(){return`import 'dotenv/config';
|
|
1107
1429
|
import { defineConfig, env } from 'prisma/config';
|
|
1108
1430
|
|
|
1109
1431
|
export default defineConfig({
|
|
@@ -1116,7 +1438,7 @@ export default defineConfig({
|
|
|
1116
1438
|
url: env('DATABASE_URL'),
|
|
1117
1439
|
},
|
|
1118
1440
|
});
|
|
1119
|
-
`}function
|
|
1441
|
+
`}function Ro(e){return`@${e}`}function zo(){return{"@repo/cache":[`packages/cache/src/index.ts`],"@repo/database":[`packages/database/src/index.ts`]}}function Bo(){return{"@/*":[`./src/*`]}}function Vo(e,t){let n=z(t.packageManager,`web`,`dev`),r=z(t.packageManager,`api`,`dev`),i=z(t.packageManager,`@repo/database`,`db:studio`),a=z(t.packageManager,`@repo/database`,`db:generate`),o=z(t.packageManager,`@repo/database`,`db:migrate`),s=z(t.packageManager,`@repo/database`,`build`),c=z(t.packageManager,`@repo/cache`,`build`),l=[`jobs`,`queue`,...t.workers.some(e=>e.kind===`webhooks`)?[`webhooks`]:[]].map(e=>z(t.packageManager,`@repo/${e}`,`build`)),u=z(t.packageManager,`@repo/observability`,`build`),d=[c,s,...t.features.telemetry?[u]:[],...t.workers.length>0?l:[]].join(` && `),f=d,p={dev:`${d} && turbo dev`,"dev:web":n,"dev:api":`${f} && ${r}`,...t.runtime===`bun`?{"start:api":`${f} && ${z(t.packageManager,`api`,`start:prod`)}`}:{},build:`turbo build`,lint:t.features.ultracite?`ultracite check && turbo lint`:`turbo lint`,test:`turbo test`,typecheck:`turbo typecheck`,check:t.features.ultracite?`ultracite check && turbo typecheck && turbo test`:`turbo typecheck && turbo test`,"db:studio":i,"db:generate":a,"db:migrate":o};return t.features.ultracite&&(p[`lint:fix`]=`ultracite fix`,p.format=`ultracite fix`),t.features.lefthook&&(p.prepare=`lefthook install`),V({name:e,description:`Monorepo com web, api NestJS e packages compartilhados gerado pelo rockcli`,packageManager:t.packageManager,sideEffects:!1,keywords:[`rockcli`,`monorepo`,`turbo`,`nestjs`],scripts:p,devDependencies:{turbo:`^2.5.4`,typescript:`^5.9.3`,...t.databaseOrm===`prisma`?{"@prisma/client":`^6.15.0`,prisma:`^6.15.0`}:{},...t.features.ultracite?{...Ca()}:{},...t.features.commitlint?{"@commitlint/cli":`^20.1.0`,"@commitlint/config-conventional":`^20.0.0`}:{},...t.features.lefthook?{lefthook:`^1.11.12`}:{}},extraFields:{workspaces:[`apps/*`,...t.workers.length>0?[`apps/workers/*`]:[],`packages/*`]}})}function Ho(){return rr({outputEntries:[`.next`],cacheEntries:[`.turbo`]})}function Uo(){return`{
|
|
1120
1442
|
"$schema": "https://turborepo.com/schema.json",
|
|
1121
1443
|
"tasks": {
|
|
1122
1444
|
"build": {
|
|
@@ -1139,28 +1461,28 @@ export default defineConfig({
|
|
|
1139
1461
|
}
|
|
1140
1462
|
}
|
|
1141
1463
|
}
|
|
1142
|
-
`}function
|
|
1464
|
+
`}function Wo(){return H({compilerOptions:{strict:!0,skipLibCheck:!0,noUncheckedIndexedAccess:!0,exactOptionalPropertyTypes:!0,forceConsistentCasingInFileNames:!0,resolveJsonModule:!0,esModuleInterop:!0,isolatedModules:!0,baseUrl:`.`,paths:zo()}})}function Go(e,t,n,r,i){return`NODE_ENV="development"
|
|
1143
1465
|
PORT=3001
|
|
1144
1466
|
${e.telemetry?`OTEL_SERVICE_NAME="${r}"
|
|
1145
1467
|
OTEL_SERVICE_VERSION="local"
|
|
1146
1468
|
LOG_LEVEL="info"
|
|
1147
1469
|
TELEMETRY_HTTP_SUCCESS_LOGS_ENABLED="false"
|
|
1148
1470
|
TELEMETRY_HTTP_SLOW_REQUEST_MS="1000"
|
|
1149
|
-
${
|
|
1471
|
+
${Pr(i)}`:``}DATABASE_URL="postgresql://docker:docker@localhost:7000/rock"
|
|
1150
1472
|
REDIS_PASSWORD="redis_password"
|
|
1151
1473
|
REDIS_URL="redis://default:redis_password@localhost:6379"
|
|
1152
1474
|
${e.betterAuth?`BETTER_AUTH_SECRET="change-this-secret-with-at-least-32-characters"
|
|
1153
1475
|
BETTER_AUTH_URL="http://localhost:3001"
|
|
1154
1476
|
CLIENT_ORIGIN="http://localhost:3000"
|
|
1155
|
-
${
|
|
1156
|
-
`}function
|
|
1477
|
+
${ta(t,n)}`:``}
|
|
1478
|
+
`}function Ko(e){let t={dev:`next dev`,build:`next build`,start:`next start`,test:`echo "No tests configured yet"`,typecheck:`tsc --noEmit -p tsconfig.json`,lint:e.features.ultracite?`ultracite check`:`tsc --noEmit -p tsconfig.json`,check:e.features.ultracite?`ultracite check && tsc --noEmit -p tsconfig.json`:`tsc --noEmit -p tsconfig.json`};return e.features.ultracite&&(t[`lint:fix`]=`ultracite fix`,t.format=`ultracite fix`),V({name:`web`,description:`Aplicacao Next.js do monorepo Rock`,packageManager:e.packageManager,sideEffects:[`**/*.css`],keywords:[`rockcli`,`web`,`nextjs`],scripts:t,dependencies:{envalid:`^8.1.0`,...to({betterAuth:e.features.betterAuth,authPlugins:e.authPlugins}),next:`^15.4.1`,react:`^19.1.0`,"react-dom":`^19.1.0`},devDependencies:{"@types/node":`^24.0.15`,"@types/react":`^19.1.8`,"@types/react-dom":`^19.1.6`,...no(),typescript:`^5.9.3`}})}function qo(){return H({extends:`../../tsconfig.base.json`,compilerOptions:{target:`ES2022`,lib:[`dom`,`dom.iterable`,`ES2022`],allowJs:!1,skipLibCheck:!0,strict:!0,noUncheckedIndexedAccess:!0,exactOptionalPropertyTypes:!0,noEmit:!0,esModuleInterop:!0,module:`ESNext`,moduleResolution:`bundler`,resolveJsonModule:!0,isolatedModules:!0,jsx:`preserve`,incremental:!0,baseUrl:`.`,paths:Bo(),plugins:[{name:`next`}]},include:[`next-env.d.ts`,`src/**/*.ts`,`src/**/*.tsx`,`.next/types/**/*.ts`],exclude:[`node_modules`]})}function Jo(){return`/** @type {import('next').NextConfig} */
|
|
1157
1479
|
const nextConfig = {
|
|
1158
1480
|
reactStrictMode: true,
|
|
1159
1481
|
typedRoutes: true,
|
|
1160
1482
|
};
|
|
1161
1483
|
|
|
1162
1484
|
export default nextConfig;
|
|
1163
|
-
`}function
|
|
1485
|
+
`}function Yo(e){return`import { cleanEnv, str } from 'envalid';
|
|
1164
1486
|
|
|
1165
1487
|
export const env = cleanEnv(process.env, {
|
|
1166
1488
|
NEXT_PUBLIC_API_URL: str({
|
|
@@ -1173,16 +1495,16 @@ export const env = cleanEnv(process.env, {
|
|
|
1173
1495
|
default: '${e}',
|
|
1174
1496
|
}),
|
|
1175
1497
|
});
|
|
1176
|
-
`}function
|
|
1498
|
+
`}function Xo(e){let t=e.workers??[];return e.hosting?.api===`cloudflare`?t.map(({name:e,queue:t})=>({name:e,queue:t})):t}function Zo(e){return!!e.messaging||Xo(e).some(e=>e.kind===`messaging`)}function Qo(e){return e.workers.some(e=>e.kind===`messaging`)}function $o(e){return e.workers.some(e=>e.kind===`webhooks`)}const es={id:`monolith`,label:`monolith`,description:`Monorepo completo com web, api NestJS e packages compartilhados`,createContext(e){return{hosting:e.hosting,projectName:e.name,projectSlug:Yn(e.name),packageManager:e.packageManager,runtime:e.runtime??`node`,databaseOrm:na(e.databaseOrm),authProviders:e.authProviders??[],authPlugins:e.authPlugins??[],telemetryAdapter:e.telemetryAdapter??`posthog`,workers:Xo(e),messaging:Zo(e),implementAuthModule:e.implementAuthModule??!1,workflows:e.workflows??[`quality`,`codeql`,`dependencyReview`],features:La(e.fullSetup,e.setupFeatures)}},files(e){let t=`packages:
|
|
1177
1499
|
- apps/*
|
|
1178
1500
|
${e.workers.length>0?` - apps/workers/*
|
|
1179
1501
|
`:``} - packages/*
|
|
1180
|
-
`,n=
|
|
1181
|
-
`})),{path:`pnpm-workspace.yaml`,content:t,condition:e=>e.packageManager===`pnpm`},...
|
|
1502
|
+
`,n=na(e.databaseOrm),r=Ua({packageManager:e.packageManager,workflows:e.workflows}),i=ba([{path:`package.json`,content:Vo(e.projectSlug,e)},{path:`tsconfig.base.json`,content:Wo()},{path:`turbo.json`,content:Uo()},{path:`.gitignore`,content:Ho()},{path:`packages/database/prisma/schema.prisma`,content:Io(),condition:()=>n===`prisma`},{path:`packages/database/prisma.config.ts`,content:Lo(),condition:()=>n===`prisma`},{path:`packages/database/drizzle.config.ts`,content:aa({envImport:`./src/env`,schemaPath:`./src/schema.ts`}),condition:()=>n===`drizzle`},...[`.env`,`.env.example`].map(e=>({path:`packages/database/${e}`,content:`DATABASE_URL="postgresql://docker:docker@localhost:7000/rock"
|
|
1503
|
+
`})),{path:`pnpm-workspace.yaml`,content:t,condition:e=>e.packageManager===`pnpm`},..._o({scope:Ro(e.projectSlug),projectSlug:e.projectSlug,workers:e.workers,packageManager:e.packageManager,runtime:e.runtime,packages:[`jobs`,`queue`,...e.features.telemetry?[`observability`]:[]],telemetry:e.features.telemetry,telemetryAdapter:e.telemetryAdapter,databaseOrm:n}),...e.features.telemetry?Br({scope:`@repo`,packageManager:e.packageManager,telemetryAdapter:e.telemetryAdapter}):[],...e.workers.length>0?Lr({scope:Ro(e.projectSlug),packages:[`jobs`,`queue`,...$o(e)?[`webhooks`]:[]],packageManager:e.packageManager,queueNames:vo(e.workers)}):[],..._r({railway:e.features.railway,vercel:e.features.vercel,webPrefix:`apps/web`,railwayOptions:{prefix:`apps/api`,watchedPackages:[`database`,`cache`],packageManager:e.packageManager,healthcheckPath:`/v1/health`,preDeployCommand:n===`prisma`?`prisma migrate deploy`:`drizzle-kit migrate`},vercelOptions:{packageManager:e.packageManager,monorepo:!0,filter:`web`}}),...Sa({hasWeb:!0,hasApi:!0,editorconfig:e.features.editorconfig,lefthook:e.features.lefthook,ultracite:e.features.ultracite,commitlint:e.features.commitlint,dockerignore:e.features.dockerignore,packageManager:e.packageManager}),{path:`commitlint.config.ts`,content:ir(),condition:e=>e.features.commitlint},{path:`docker-compose.yml`,content:ar(),condition:e=>e.features.dockerCompose},...r,{path:`apps/web/package.json`,content:Ko(e)},{path:`apps/web/tsconfig.json`,content:qo()},{path:`apps/web/next.config.mjs`,content:Jo()},{path:`apps/web/next-env.d.ts`,content:`/// <reference types="next" />
|
|
1182
1504
|
/// <reference types="next/image-types/global" />
|
|
1183
|
-
`},{path:`apps/web/src/env.ts`,content:
|
|
1505
|
+
`},{path:`apps/web/src/env.ts`,content:Yo(e.projectName)},...eo({prefix:`apps/web`,projectName:e.projectName,authProviders:e.authProviders,authPlugins:e.authPlugins,betterAuth:e.features.betterAuth}),{path:`apps/web/.env`,content:`NEXT_PUBLIC_APP_NAME="${e.projectName}"
|
|
1184
1506
|
`},{path:`apps/web/.env.example`,content:`NEXT_PUBLIC_APP_NAME="${e.projectName}"
|
|
1185
|
-
`},{path:`apps/api/package.json`,content:
|
|
1507
|
+
`},{path:`apps/api/package.json`,content:bo(e)},{path:`apps/api/nest-cli.json`,content:ma()},{path:`apps/api/tsconfig.json`,content:_a({extends:`../../tsconfig.base.json`,packageManager:e.packageManager,runtime:e.runtime})},{path:`apps/api/tsconfig.build.json`,content:ha()},{path:`apps/api/src/app.module.ts`,content:Li(e.implementAuthModule,e.features.telemetry,e.messaging,`@repo/observability`)},{path:`apps/api/src/env.ts`,content:xo(e.features,e.authProviders,e.authPlugins,e.projectSlug,e.telemetryAdapter)},{path:`apps/api/src/auth.ts`,content:$i(n,e.authProviders,`import { DatabaseService } from '@repo/database';`,e.authPlugins,e.messaging),condition:e=>e.features.betterAuth},{path:`apps/api/src/modules/auth/auth.module.ts`,content:Ri(`../database/database.service`,e.messaging),condition:e=>e.features.betterAuth&&e.implementAuthModule},{path:`apps/api/src/modules/auth/auth-session.controller.ts`,content:zi(),condition:e=>e.features.betterAuth&&e.implementAuthModule},{path:`apps/api/src/modules/cache/cache.module.ts`,content:wo()},{path:`apps/api/src/modules/cache/cache.service.ts`,content:To()},{path:`apps/api/src/modules/database/database.module.ts`,content:So()},{path:`apps/api/src/modules/database/database.service.ts`,content:Co()},...ya({prefix:`apps/api`,projectSlug:e.projectSlug,messaging:e.messaging,authModule:e.implementAuthModule,inlineAuth:e.features.betterAuth&&!e.implementAuthModule,projectName:e.projectName,telemetry:e.features.telemetry,telemetryAdapter:e.telemetryAdapter,observability:`@repo/observability`}),{path:`apps/api/.env.example`,content:Go(e.features,e.authProviders,e.authPlugins,e.projectSlug,e.telemetryAdapter)},{path:`apps/api/.env`,content:Go(e.features,e.authProviders,e.authPlugins,e.projectSlug,e.telemetryAdapter)},{path:`apps/api/Dockerfile`,content:``,condition:e=>e.features.dockerfile},{path:`packages/cache/package.json`,content:Do(e)},{path:`packages/cache/tsconfig.json`,content:H({extends:`./tsconfig.build.json`,compilerOptions:{noEmit:!0}})},{path:`packages/cache/tsconfig.build.json`,content:Eo()},{path:`packages/cache/src/index.ts`,content:Oo()},{path:`packages/cache/src/env.ts`,content:ko()},{path:`packages/cache/src/cache.service.ts`,content:Ao()},{path:`packages/database/package.json`,content:jo(e)},{path:`packages/database/tsconfig.json`,content:H({extends:`./tsconfig.build.json`,compilerOptions:{noEmit:!0}})},{path:`packages/database/tsconfig.build.json`,content:Eo()},{path:`packages/database/src/index.ts`,content:Mo()},{path:`packages/database/src/env.ts`,content:No()},{path:`packages/database/src/database.service.ts`,content:n===`prisma`?Po():Fo()},...n===`drizzle`?pa({schemaPath:`packages/database/src/schema.ts`,tablesDir:`packages/database/src/tables`,schemaToTables:`./tables`,betterAuth:e.features.betterAuth,authPlugins:e.authPlugins,webhooks:$o(e)}):[]].map(t=>({...t,...`content`in t&&t.content!==void 0?{content:t.content.replaceAll(`@repo/`,`${Ro(e.projectSlug)}/`)}:{}})),!!e.messaging&&!Qo(e)),a=Qo(e)?yo(i,{scope:Ro(e.projectSlug),projectSlug:e.projectSlug}):i;return $o(e)?co(a,{scope:Ro(e.projectSlug),databaseOrm:n,routes:e.features.betterAuth&&e.implementAuthModule,telemetry:e.features.telemetry}):a},postCreateSteps(e){return[...e.features.lefthook?[`${Vn(e.packageManager,`lefthook install`)}`]:[],...Yi(e.authPlugins)]}};function ts(e,t,n,r){let i={dev:`next dev`,build:`next build`,start:`next start`,test:`echo "No tests configured yet"`,typecheck:`tsc --noEmit -p tsconfig.json`,lint:n.ultracite?`ultracite check`:`tsc --noEmit -p tsconfig.json`,check:n.ultracite?`ultracite check && tsc --noEmit -p tsconfig.json`:`tsc --noEmit -p tsconfig.json`};return n.ultracite&&(i[`lint:fix`]=`ultracite fix`,i.format=`ultracite fix`),n.lefthook&&(i.prepare=`lefthook install`),V({name:e,description:`Projeto web com Next.js gerado pelo rockcli`,packageManager:t,sideEffects:[`**/*.css`],keywords:[`rockcli`,`nextjs`,`web`],scripts:i,dependencies:{envalid:`^8.1.0`,...to({betterAuth:n.betterAuth,authPlugins:r}),next:`^15.4.1`,react:`^19.1.0`,"react-dom":`^19.1.0`},devDependencies:{"@types/node":`^24.0.15`,"@types/react":`^19.1.8`,"@types/react-dom":`^19.1.6`,...no(),typescript:`^5.9.3`,...n.ultracite?{...Ca()}:{},...n.lefthook?{lefthook:`^1.11.12`}:{},...n.commitlint?{"@commitlint/cli":`^20.1.0`,"@commitlint/config-conventional":`^20.0.0`}:{}}})}function ns(){return H({compilerOptions:{target:`ES2022`,lib:[`dom`,`dom.iterable`,`ES2022`],allowJs:!1,skipLibCheck:!0,strict:!0,noUncheckedIndexedAccess:!0,exactOptionalPropertyTypes:!0,noEmit:!0,esModuleInterop:!0,module:`ESNext`,moduleResolution:`bundler`,resolveJsonModule:!0,isolatedModules:!0,jsx:`preserve`,incremental:!0,baseUrl:`.`,paths:{"@/*":[`./src/*`]},plugins:[{name:`next`}]},include:[`next-env.d.ts`,`src/**/*.ts`,`src/**/*.tsx`,`.next/types/**/*.ts`],exclude:[`node_modules`]})}const rs=[es,{id:`web`,label:`web`,description:`Projeto web isolado com Next.js`,createContext(e){return{hosting:e.hosting,projectName:e.name,projectSlug:Yn(e.name),packageManager:e.packageManager,runtime:e.runtime??`node`,authProviders:e.authProviders??[],authPlugins:e.authPlugins??[],telemetryAdapter:e.telemetryAdapter??`posthog`,workers:e.workers??[],implementAuthModule:!1,workflows:e.workflows??[`quality`,`codeql`,`dependencyReview`],features:La(e.fullSetup,e.setupFeatures)}},files(e){return[{path:`package.json`,content:ts(e.projectSlug,e.packageManager,e.features,e.authPlugins)},{path:`tsconfig.json`,content:ns()},{path:`next.config.mjs`,content:`/** @type {import('next').NextConfig} */
|
|
1186
1508
|
const nextConfig = {
|
|
1187
1509
|
reactStrictMode: true,
|
|
1188
1510
|
typedRoutes: true,
|
|
@@ -1191,7 +1513,7 @@ const nextConfig = {
|
|
|
1191
1513
|
export default nextConfig;
|
|
1192
1514
|
`},{path:`next-env.d.ts`,content:`/// <reference types="next" />
|
|
1193
1515
|
/// <reference types="next/image-types/global" />
|
|
1194
|
-
`},...
|
|
1516
|
+
`},...eo({prefix:``,projectName:e.projectName,authProviders:e.authProviders,authPlugins:e.authPlugins,betterAuth:e.features.betterAuth}),{path:`src/env.ts`,content:`import { cleanEnv, str } from 'envalid';
|
|
1195
1517
|
|
|
1196
1518
|
export const env = cleanEnv(process.env, {
|
|
1197
1519
|
NEXT_PUBLIC_API_URL: str({
|
|
@@ -1206,13 +1528,8 @@ export const env = cleanEnv(process.env, {
|
|
|
1206
1528
|
});
|
|
1207
1529
|
`},{path:`.env`,content:`NEXT_PUBLIC_APP_NAME="${e.projectName}"
|
|
1208
1530
|
`},{path:`.env.example`,content:`NEXT_PUBLIC_APP_NAME="${e.projectName}"
|
|
1209
|
-
`},{path:`.gitignore`,content
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
RUN ${e.packageManager} install
|
|
1213
|
-
EXPOSE 3000
|
|
1214
|
-
CMD ["${e.packageManager}", "run", "dev"]
|
|
1215
|
-
`,condition:e=>e.features.dockerfile},...Qi({packageManager:e.packageManager,workflows:e.workflows})]}},ua];function fo(){let e={monolith:`Monolito Modular`,api:`API`,web:`Web`};return uo.map(t=>({value:t.id,label:e[t.id],hint:t.description}))}function po(e){return uo.find(t=>t.id===e)}async function mo(e,t){try{await R(t,[`run`,`format`],{cwd:e})}catch{return!1}return!0}async function ho(e){try{await R(`git`,[`init`,`--initial-branch=main`],{cwd:e})}catch{await R(`git`,[`init`],{cwd:e}),await R(`git`,[`symbolic-ref`,`HEAD`,`refs/heads/main`],{cwd:e})}}async function go(e){let t=po(e.templateId),n=Jn({runtime:e.runtime,packageManager:e.packageManager,templateId:e.templateId,apiHosting:e.hosting?.api});if(n)throw Error(n);if(!t)throw Error(`Template desconhecido: ${e.templateId}`);let r=t.createContext({hosting:e.hosting,name:e.name,packageManager:e.packageManager,runtime:e.runtime,fullSetup:e.fullSetup,setupFeatures:e.setupFeatures,authProviders:e.authProviders,authPlugins:e.authPlugins,telemetryAdapter:e.telemetryAdapter,workers:e.workers,messaging:e.messaging,implementAuthModule:e.implementAuthModule,databaseOrm:e.databaseOrm,workflows:e.workflows}),i=s.resolve(e.cwd,e.name);await Pn(i),await Fn(i,zr(yr(vr(Lr(Rr(mr(t.files(r).filter(e=>!e.condition||e.condition(r)),r,e.templateId)),r,e.templateId)),e.envValues))),await ho(i);let a=!1;e.installDependencies&&(await Br(i,e.packageManager,{lefthook:r.features.lefthook}),a=await mo(i,e.packageManager));let o=[...a?[]:[`${e.packageManager} run format`],e.installDependencies?`${e.packageManager} run dev`:`${e.packageManager===`pnpm`?`pnpm install && `:`bun install && `}${e.packageManager} run dev`,...(t.postCreateSteps?.(r)??[]).filter(t=>!e.installDependencies||!t.includes(`lefthook install`))];return{targetDir:i,projectDirectoryName:s.basename(i),nextSteps:o}}function _o(e,t,n,r){let i=e.options?.[t],a={apiHosting:`--api-hosting`,webHosting:`--web-hosting`,webType:`--web-type`}[t];if(i!==void 0&&!n.includes(i))throw Error(`Valor invalido para ${a}: use ${n.join(`, `)}.`);if(i!==void 0&&(t===`apiHosting`&&r.templateId===`web`||t!==`apiHosting`&&r.templateId===`api`))throw Error(`${a} nao se aplica ao template ${r.templateId}.`);if(e.options?.serverless&&t!==`webType`&&i!==void 0&&i!==`cloudflare`)throw Error(`Conflito: --serverless exige ${a} cloudflare.`);return i}const vo=[`vinext`,`opennext`],yo=[{id:`apiHosting`,fromArgs:(e,t)=>{let n=_o(e,`apiHosting`,[`traditional`,`railway`,`cloudflare`],t)??(e.options?.serverless&&t.templateId!==`web`?`cloudflare`:void 0),r=Jn({runtime:t.runtime,apiHosting:n});if(r)throw Error(r);return t.runtime===`bun`?n??`traditional`:n},when:e=>e.templateId!==`web`,defaultValue:()=>`traditional`,label:`Hospedagem da API`,prompt:(e,t)=>L({message:`Deseja usar Serverless na API?`,initialValue:t??`traditional`,options:[{value:`traditional`,label:`Nao, manter servidor tradicional`},{value:`cloudflare`,label:`Sim, Cloudflare Workers`}]}),summary:e=>e?`Hospedagem API: ${e}`:void 0},{id:`webType`,fromArgs:(e,t)=>_o(e,`webType`,[`application`,`landing`],t),when:e=>e.templateId!==`api`,defaultValue:()=>`application`,label:`Tipo de website`,prompt:(e,t)=>L({message:`Qual tipo de website deseja gerar?`,initialValue:t??`application`,options:[{value:`application`,label:`Aplicacao com servidor (login/dashboard opcionais)`},{value:`landing`,label:`Landing page estatica`}]}),summary:e=>e?`Website: ${e}`:void 0},{id:`webHosting`,fromArgs:(e,t)=>_o(e,`webHosting`,[`traditional`,`vercel`,`cloudflare`],t)??(e.options?.serverless&&t.templateId!==`api`?`cloudflare`:void 0),when:e=>e.templateId!==`api`,defaultValue:()=>`traditional`,label:`Hospedagem do website`,prompt:(e,t)=>L({message:`Deseja hospedar o website no Cloudflare?`,initialValue:t??`traditional`,options:[{value:`traditional`,label:`Nao, manter hospedagem tradicional`},{value:`cloudflare`,label:`Sim, Cloudflare`}]}),summary:e=>e?`Hospedagem web: ${e}`:void 0},{id:`webAdapter`,fromArgs:(e,t)=>{let n=e.options?.webAdapter;if(n!==void 0){if(!vo.includes(n))throw Error(`Valor invalido para --web-adapter: use ${vo.join(`, `)}.`);if(t.webHosting!==`cloudflare`)throw Error(`--web-adapter exige website no Cloudflare.`);return n}},when:e=>e.webHosting===`cloudflare`,defaultValue:()=>`vinext`,label:`Adapter web`,prompt:(e,t)=>L({message:`Qual adapter deseja usar no Cloudflare?`,initialValue:t??`vinext`,options:e.webType===`landing`?[{value:`vinext`,label:`vinext (Workers estatico)`},{value:`opennext`,label:`Pages estatico (legado)`}]:[{value:`vinext`,label:`vinext (Vite, recomendado)`},{value:`opennext`,label:`OpenNext (mais maduro)`}]}),summary:e=>e?`Adapter web: ${e}`:void 0},{id:`kv`,fromArgs:(e,t)=>{if(e.options?.kv&&t.apiHosting!==`cloudflare`)throw Error(`--kv exige API no Cloudflare.`);return e.options?.kv},when:e=>e.apiHosting===`cloudflare`,fallback:!1,defaultValue:()=>!1,label:`Cache KV`,prompt:(e,t)=>L({message:`Deseja usar cache Cloudflare KV?`,initialValue:t??!1,options:[{value:!1,label:`Nao`},{value:!0,label:`Sim, cache KV`}]})}];function bo(e){if(e.webType===`landing`&&e.setupFeatures?.includes(`betterAuth`)&&(e.webType=`application`),e.apiHosting===`railway`)for(let t of[`railway`,`dockerfile`])e.setupFeatures.includes(t)||e.setupFeatures.push(t);return e.webHosting===`vercel`&&!e.setupFeatures.includes(`vercel`)&&e.setupFeatures.push(`vercel`),e}const xo={templateId:`o template (rock new <web|api|monolith> <nome> --yes)`,projectName:`o nome (rock new <template> <nome> --yes)`};function So(e){return Array.isArray(e)?e.length>0?e.map(e=>typeof e==`object`&&e&&`name`in e?String(e.name):String(e)).join(`, `):`nenhum`:typeof e==`boolean`?e?`sim`:`não`:e===void 0?``:String(e)}async function Co(e,t,n){let r=B(await L({message:`Revise as respostas. Deseja alterar alguma?`,initialValue:-1,options:[{value:-1,label:`Tudo certo, gerar o projeto`},...t.map(t=>{let r=e[t],i=n[r.id];return{value:t,label:`Alterar: ${r.label??r.id}`,hint:r.review?.(i)??So(i)}})]}),`Operacao cancelada.`);return r===-1?void 0:r}async function wo(e,t,n=Co){let r={},i={},a=[],o=0;for(;;){for(let n=o;n<e.length;n++){let o=e[n],s=await o.fromArgs?.(t,r);if(s!==void 0)r[o.id]=s;else if(o.when&&!await o.when(r))o.fallback!==void 0&&(r[o.id]=o.fallback);else if(t.options?.yes){if(!o.defaultValue)throw Error(`Com --yes, informe ${xo[o.id]??o.id}.`);r[o.id]=o.defaultValue(r)}else r[o.id]=B(await o.prompt(r,i[o.id]),`Operacao cancelada.`),a.push(n)}if(t.options?.yes||a.length===0)break;let s=await n(e,a,r);if(s===void 0)break;for(let t of e.slice(s))r[t.id]!==void 0&&(i[t.id]=r[t.id]),delete r[t.id];a=a.filter(e=>e<s),o=s}return r.apiHosting!==void 0||r.webHosting!==void 0?bo(r):r}function To(e,t){return e.map(e=>e.summary?.(t[e.id],t)).filter(e=>!!e)}function Eo(e){let{answers:t,result:n,installedSkills:r,skillCommands:i,steps:a}=e;I([...To(a,t),`${z.default.green(`Git:`)} repositorio criado na branch main`].join(`
|
|
1216
|
-
`),z.default.bold(`Scaffold pronto`)),F([z.default.bold(z.default.green(`Projeto gerado bonitinho.`)),``,`${z.default.green(`Pasta:`)} ${n.targetDir}`,``,z.default.bold(`Proximos comandos`),`cd ${n.projectDirectoryName}`,...n.nextSteps,...r.length>0||i.length>0?[``,z.default.bold(`Skills globais`),...r.length>0?[`Instaladas: ${r.join(`, `)}`]:[],...i.length>0?[`Falha ao instalar; tente novamente:`,...i]:[]]:[]].join(`
|
|
1217
|
-
`))}function Do(e){if(e.exitCode!==0)return[];try{return JSON.parse(e.stdout).map(e=>e.name?e.name.toLowerCase():e.path?.split(/[\\/]/).filter(Boolean).at(-1)?.toLowerCase()??``)}catch{return[]}}async function Oo(e,t,r=n){let i=await Promise.all([[`list`,`--json`],[`list`,`--global`,`--json`]].map(async e=>{try{return Do(await r(`npx`,[`--yes`,`skills`,...e],{cwd:t}))}catch{return[]}})),a=new Set(i.flat());return e.filter(e=>!a.has(e.skill.toLowerCase()))}function ko(e){return Bi(e.templateId).filter(t=>t.id===`railway`&&e.apiHosting===`cloudflare`||t.id===`vercel`&&e.webHosting===`cloudflare`?!1:t.id===`dockerfile`||t.id===`dockerignore`?e.templateId!==`web`&&e.apiHosting!==`cloudflare`||e.templateId===`web`&&e.webHosting!==`cloudflare`:t.id!==`dockerCompose`||e.templateId!==`web`||e.webHosting!==`cloudflare`)}function Ao(){return[{id:`setupFeatures`,defaultValue:e=>ko(e).filter(e=>e.defaultSelected).map(e=>e.id),label:`Extras de scaffold`,prompt:(e,t)=>{let n=ko(e);return P({message:`Quais extras de scaffold voce quer incluir?`,initialValues:t??n.filter(e=>e.defaultSelected).map(e=>e.id),options:n.map(e=>({value:e.id,label:e.label,hint:e.hint}))})},summary:e=>`${z.default.green(`Extras:`)} ${e.length>0?e.join(`, `):`nenhum`}`}]}function jo(e){return e?.clientId&&e.clientSecret?`credenciais no .env`:`preencha ROCKFELLER_CLIENT_ID e ROCKFELLER_CLIENT_SECRET no .env`}function X(e){return e===`api`||e===`monolith`}function Mo(e,t,n){if(t!==void 0){if(!n.includes(t))throw Error(`Valor invalido para ${e}: ${z.default.yellow(t)} (use ${n.join(` ou `)}).`);return t}}function Z(e){return e}const No=[{value:`emailAndPassword`,label:`Email e senha`,hint:`Login tradicional com credenciais.`},{value:`google`,label:`Google`,hint:`OAuth com Google.`},{value:`github`,label:`GitHub`,hint:`OAuth com GitHub.`},{value:`discord`,label:`Discord`,hint:`OAuth com Discord.`}],Po=[{value:`quality`,label:`Verificações de qualidade`,hint:`Executa lint, verificação de tipos, testes e build em cada push e pull request.`},{value:`codeql`,label:`Análise de segurança (CodeQL)`,hint:`Procura vulnerabilidades no código JavaScript e TypeScript.`},{value:`dependencyReview`,label:`Revisão de dependências`,hint:`Verifica alterações e possíveis riscos nas dependências de cada pull request.`}],Fo=[`pnpm`,`bun`],Io=[`prisma`,`drizzle`];function Lo(e){if(!e?.trim())return`Informe um nome de projeto.`;if(/[<>:"/\\|?*\x00-\x1F]/.test(e))return`Use um nome de pasta valido.`}function Ro(e){let t=/* @__PURE__ */ new Set;return e.split(`,`).map(e=>Gn(e)).filter(e=>!e||t.has(e)?!1:(t.add(e),!0)).map(e=>({name:e,queue:e}))}const zo=[Z({id:`templateId`,fromArgs:e=>{if(e.template){if(!po(e.template))throw Error(`Template desconhecido: ${z.default.yellow(e.template)}`);return e.template}},label:`Template`,prompt:(e,t)=>L({message:`Qual base você quer gerar?`,...t===void 0?{}:{initialValue:t},options:fo()}),summary:e=>`${z.default.green(`Template:`)} ${e}`}),Z({id:`projectName`,fromArgs:e=>{let t=e.name??e.options?.name,n=t===void 0?void 0:Lo(t);if(n)throw Error(n);return t},label:`Nome do projeto`,prompt:(e,t)=>Yt({message:`Qual será o nome do projeto? (O nome será também o da pasta dele)`,placeholder:`my-rock-app`,...t===void 0?{}:{initialValue:t},validate:Lo})}),Z({id:`runtime`,fromArgs:(e,t)=>{let n=Mo(`--runtime`,e.options?.runtime,qn),r=Jn({runtime:n,templateId:t.templateId});if(r)throw Error(r);return n},when:e=>X(e.templateId),fallback:`node`,defaultValue:()=>`node`,label:`Runtime`,prompt:(e,t)=>L({message:`Em qual runtime a API e os workers vão rodar?`,initialValue:t??`node`,options:[{value:`node`,label:`Node.js`,hint:`default · pnpm ou bun`},{value:`bun`,label:`Bun`,hint:`roda o TypeScript direto; usa o Bun como package manager`}]}),summary:(e,t)=>X(t.templateId)?`${z.default.green(`Runtime:`)} ${e}`:void 0}),Z({id:`packageManager`,fromArgs:(e,t)=>{let n=Mo(`--package-manager`,e.options?.packageManager,Fo),r=Jn({runtime:t.runtime,packageManager:n});if(r)throw Error(r);return n},when:e=>e.runtime!==`bun`,fallback:`bun`,defaultValue:()=>`pnpm`,label:`Package manager`,prompt:(e,t)=>L({message:`Qual package manager deseja usar?`,initialValue:t??`pnpm`,options:[{value:`pnpm`,label:`pnpm`,hint:`default`},{value:`bun`,label:`bun`}]}),summary:e=>`${z.default.green(`Package manager:`)} ${e}`}),...yo,Z({id:`databaseOrm`,fromArgs:e=>Mo(`--orm`,e.options?.orm,Io),when:e=>X(e.templateId),defaultValue:()=>`drizzle`,label:`ORM`,prompt:(e,t)=>L({message:`Qual ORM deseja usar no banco?`,initialValue:t??`drizzle`,options:[{value:`prisma`,label:`Prisma`},{value:`drizzle`,label:`Drizzle (padrão)`}]}),summary:e=>e?`${z.default.green(`ORM:`)} ${e}`:void 0}),Z({id:`installDependencies`,fromArgs:e=>e.options?.install!==!1&&void 0,defaultValue:()=>!0,label:`Instalar dependências`,prompt:(e,t)=>Rt({message:`Deseja instalar os pacotes agora?`,initialValue:t??!0}),summary:e=>`${z.default.green(`Dependencias:`)} ${e?`instaladas`:`pendentes`}`}),...Ao(),Z({id:`messaging`,when:e=>X(e.templateId),fromArgs:e=>e.options?.messaging,fallback:!1,defaultValue:()=>!1,label:`Messaging`,prompt:(e,t)=>L({message:`Deseja incluir o módulo de messaging para envio de e-mails, webpush, SMS e mensagens de WhatsApp?`,initialValue:t??!1,options:[{value:!1,label:`Não incluir`,hint:`Sem o módulo de messaging.`},{value:!0,label:`Incluir módulo de messaging`,hint:`Habilita os canais de e-mail, webpush, SMS e WhatsApp.`}]}),summary:(e,t)=>X(t.templateId)?`${z.default.green(`Messaging:`)} ${e?`incluido`:`desativado`}`:void 0}),Z({id:`workflows`,defaultValue:()=>Po.map(e=>e.value),label:`Workflows do GitHub`,prompt:(e,t)=>P({message:`Quais workflows do GitHub voce quer incluir?`,initialValues:t??Po.map(e=>e.value),options:Po}),summary:e=>`${z.default.green(`Workflows:`)} ${e.length>0?e.map(e=>Po.find(t=>t.value===e)?.label??e).join(`, `):`nenhum`}`}),Z({id:`authProviders`,when:e=>(e.setupFeatures??[]).includes(`betterAuth`),fallback:[],defaultValue:()=>[],label:`Auth providers`,prompt:(e,t)=>P({message:`Quais providers do Better Auth você quer habilitar? (opcional; deixe vazio para usar apenas SSO ou plugins)`,required:!1,initialValues:t??[],options:No}),summary:e=>e.length>0?`${z.default.green(`Auth providers:`)} ${e.join(`, `)}`:void 0}),Z({id:`telemetryAdapter`,when:e=>(e.setupFeatures??[]).includes(`telemetry`),fallback:`posthog`,defaultValue:()=>`posthog`,label:`Telemetria`,prompt:(e,t)=>L({message:`Qual destino de telemetria voce quer usar?`,initialValue:t??`posthog`,options:[{value:`posthog`,label:`PostHog`,hint:`default · eventos de produto e excecoes`},{value:`betterstack`,label:`Better Stack`,hint:`logs, metricas, traces e erros via OTLP`}]}),summary:(e,t)=>t.setupFeatures.includes(`telemetry`)?`${z.default.green(`Telemetry:`)} ${e}`:void 0}),Z({id:`authPlugins`,when:e=>(e.setupFeatures??[]).includes(`betterAuth`),fallback:[],defaultValue:()=>[],label:`Auth plugins`,prompt:(e,t)=>P({message:`Quais plugins do Better Auth voce quer habilitar?`,required:!1,initialValues:t??[],options:ei.filter(t=>t.value!==`magicLink`||e.messaging)}),summary:e=>e.length>0?`${z.default.green(`Auth plugins:`)} ${e.join(`, `)}`:void 0}),Z({id:`rockfellerSso`,when:e=>X(e.templateId)&&(e.authPlugins??[]).includes(`rockfellerSso`),defaultValue:()=>({clientId:``,clientSecret:``}),label:`Credenciais do Rockfeller SSO`,prompt:async(e,t)=>{let n=await Yt({message:`Qual é o client ID do Rockfeller SSO? (opcional; vazio para preencher depois no .env)`,...t===void 0?{}:{initialValue:t.clientId},defaultValue:``});if(typeof n!=`string`)return n;let r=await Wt({message:`Qual é o client secret do Rockfeller SSO? (opcional; vazio para preencher depois no .env)`});return typeof r==`symbol`?r:{clientId:n.trim(),clientSecret:(r??``).trim()}},review:e=>jo(e),summary:e=>e?`${z.default.green(`Rockfeller SSO:`)} ${jo(e)}`:void 0}),Z({id:`implementAuthModule`,when:e=>(e.setupFeatures??[]).includes(`betterAuth`)&&X(e.templateId),fallback:!1,defaultValue:()=>!1,label:`Implementação de auth`,prompt:(e,t)=>L({message:`Como voce quer sair do scaffold de auth?`,initialValue:t??!1,options:[{value:!1,label:`So configurar Better Auth`,hint:`Gera a instancia e as rotas base, sem modulo Nest pronto.`},{value:!0,label:`Implementar modulo NestJS`,hint:`Usa nestjs-better-auth com modulo e guard prontos.`}]}),summary:(e,t)=>t.setupFeatures.includes(`betterAuth`)&&X(t.templateId)?`${z.default.green(`Auth implementacao:`)} ${e?`modulo NestJS com nestjs-better-auth`:`instancia Better Auth base`}`:void 0}),Z({id:`workers`,fromArgs:(e,t)=>{if(e.options?.queues!==void 0){if(t.apiHosting!==`cloudflare`)throw Error(`--queues exige API no Cloudflare.`);return Ro(e.options.queues)}},when:e=>e.templateId===`monolith`||e.apiHosting===`cloudflare`,fallback:[],defaultValue:()=>[],label:`Workers e filas`,prompt:async(e,t)=>{if(e.apiHosting===`cloudflare`){let e=await L({message:`Deseja incluir filas Cloudflare Queues?`,initialValue:(t?.length??0)>0,options:[{value:!1,label:`Nao`},{value:!0,label:`Sim`}]});if(typeof e==`symbol`)return e;if(!e)return[]}let n=await Yt({message:e.apiHosting===`cloudflare`?`Quais filas Cloudflare deseja criar? (nomes separados por virgula)`:`Quais workers BullMQ voce quer criar? (nomes separados por virgula, vazio para nenhum)`,placeholder:`emails, webhooks`,...t===void 0?{}:{initialValue:t.map(e=>e.name).join(`, `)},defaultValue:``});return typeof n==`string`?Ro(n):n},summary:e=>e.length>0?`${z.default.green(`Workers:`)} ${e.map(e=>e.name).join(`, `)}`:void 0}),Z({id:`skills`,defaultValue:()=>[],label:`Skills recomendadas`,prompt:async(t,n)=>{let r=e(t.templateId),i=Kt();i.start(`Buscando skills recomendadas ainda não instaladas...`);let a=await Oo(r,process.cwd());return i.stop(a.length>0?`${a.length} skill(s) recomendada(s) disponível(is)`:`Todas as skills recomendadas já estão instaladas`),a.length===0?[]:P({message:`Quais skills recomendadas deseja incluir? (opcional)`,required:!1,initialValues:n??[],options:a.map(e=>({value:e.id,label:e.label,hint:e.description}))})},summary:e=>`${z.default.green(`Skills:`)} ${e.length>0?e.join(`, `):`nenhuma`}`})];function Bo(t){t.command(`new [template] [name]`).aliases([`generate`,`gen`,`create`]).description(`Cria uma nova base de projeto a partir de um template`).option(`-n, --name <name>`,`Nome do projeto`).option(`-y, --yes`,`Sem perguntas: usa os padroes (exige template e nome)`).option(`--package-manager <manager>`,`pnpm ou bun`).option(`--runtime <runtime>`,`node ou bun: onde a API e os workers rodam (api e monolith)`).option(`--no-install`,`Nao instala as dependencias`).option(`--orm <orm>`,`prisma ou drizzle (api e monolith)`).option(`--serverless`,`Hospeda todos os apps no Cloudflare Workers/Pages`).option(`--api-hosting <hosting>`,`traditional, railway ou cloudflare`).option(`--web-hosting <hosting>`,`traditional, vercel ou cloudflare`).option(`--web-type <type>`,`application ou landing (estatica)`).option(`--web-adapter <adapter>`,`vinext ou opennext (website no Cloudflare)`).option(`--messaging`,`Inclui modulo opcional de envio de e-mail`).option(`--kv`,`Habilita cache Cloudflare KV na API serverless`).option(`--queues <names>`,`Filas Cloudflare, nomes separados por virgula`).action(async(t,n,r)=>{let i=await wo(zo,{template:t,name:n,options:r}),a=Gi({templateId:i.templateId,features:i.setupFeatures}),o=Kt();o.start(`Gerando arquivos...`);try{let t=await go({name:i.projectName.trim(),hosting:{api:i.apiHosting,web:i.webHosting,webType:i.webType,webAdapter:i.webAdapter,kv:i.kv},templateId:i.templateId,packageManager:i.packageManager,runtime:i.runtime,installDependencies:i.installDependencies,fullSetup:Ki(a,i.templateId),setupFeatures:i.setupFeatures,authProviders:i.authProviders,authPlugins:i.authPlugins,telemetryAdapter:i.telemetryAdapter,workers:i.workers,messaging:i.messaging,implementAuthModule:i.implementAuthModule,databaseOrm:i.databaseOrm,workflows:i.workflows,envValues:{ROCKFELLER_CLIENT_ID:i.rockfellerSso?.clientId??``,ROCKFELLER_CLIENT_SECRET:i.rockfellerSso?.clientSecret??``},cwd:process.cwd()}),n=await Hr(e(i.templateId).filter(e=>i.skills.includes(e.id)));o.stop(`Projeto criado em ${z.default.cyan(t.targetDir)}`),Eo({steps:zo,answers:i,result:t,installedSkills:n.filter(e=>!e.error).map(e=>e.skill.label),skillCommands:Vr(n.filter(e=>e.error).map(e=>e.skill))})}catch(e){throw o.stop(z.default.red(`Falha ao criar projeto.`)),e}})}const Vo=[[`node`,`Node.js`],[`npm`,`npm`],[`npx`,`npx`],[`bun`,`Bun`],[`pnpm`,`pnpm`],[`cargo`,`Cargo`],[`git`,`Git`],[`claude`,`Claude Code`],[`codex`,`Codex CLI`],[`curl`,`curl`],[`code-review-graph`,`code-review-graph`]];async function Ho(e,t={}){let n=await Promise.all(Vo.map(async([n,r])=>Wo(n,r,e,t))),r=t.homedir?.()??ae(),i=[s.join(r,`.claude`,`settings.json`),s.join(r,`.claude`,`CLAUDE.md`),s.join(r,`.codex`,`AGENTS.md`),s.join(r,`.codex`,`config.toml`)],a=(await Promise.all(i.map(async e=>await Ko(e)?e:void 0))).filter(e=>!!e);return{platform:process.platform,architecture:process.arch,shell:process.env.SHELL??process.env.ComSpec??`desconhecido`,tools:n,configFiles:a}}async function Uo(e,t=process.cwd()){try{return(await n(e,[`--version`],{cwd:t})).exitCode===0}catch{return!1}}async function Wo(e,t,r,i){try{let a=await(i.run??((e,t,i)=>n(e,t,{cwd:i?.cwd??r})))(e,[`--version`],{cwd:r}),o=`${a.stdout}\n${a.stderr}`.trim();if(a.exitCode===0)return{name:t,command:e,available:!0,version:Go(o)}}catch{}return{name:t,command:e,available:!1}}function Go(e){return e.split(/\r?\n/,1)[0]?.trim()||void 0}async function Ko(e){try{return await y(e),!0}catch{return!1}}async function qo(e={}){let t=e.home??ae(),n=new Date(e.now??Date.now()).toISOString().replaceAll(`:`,`-`),r=[s.join(t,`.claude`,`settings.json`),s.join(t,`.claude`,`CLAUDE.md`),s.join(t,`.codex`,`AGENTS.md`),s.join(t,`.codex`,`config.toml`)],i=[];for(let e of r)try{await y(e);let t=`${e}.rock-backup-${n}`;await x(s.dirname(t),{recursive:!0}),await b(e,t),i.push(t)}catch{}return i}async function Jo(e){let t=e.dependencies?.run??((t,r,i)=>n(t,r,{cwd:i?.cwd??e.cwd})),r=`code-review-graph`,i=[`build`];if(e.dryRun)return{status:`ok`,message:`Atualização do code-review graph planejada.`,commands:[`${r} ${i.join(` `)}`]};try{let n=await t(r,i,{cwd:e.cwd});return n.exitCode===0?{status:`ok`,message:`Code-review graph atualizado.`,commands:[`${r} ${i.join(` `)}`]}:{status:`error`,message:`A atualização do code-review graph falhou.`,details:[n.stderr.trim()||n.stdout.trim()].filter(Boolean),commands:[`${r} ${i.join(` `)}`]}}catch{return{status:`warn`,message:`code-review-graph não está instalado.`,details:["Instale-o separadamente e execute `code-review-graph build` quando necessário."],commands:[]}}}const Yo=`https://raw.githubusercontent.com/rtk-ai/rtk/master/install.sh`;async function Xo(e){let t=e.dependencies?.run??((t,r,i)=>n(t,r,{cwd:i?.cwd??e.cwd})),r=[],i=await Qo(t,e.cwd);if(i)return{status:`ok`,message:`RTK ja esta instalado (${i}).`,commands:r};let a=await $o(t,`rtk`,e.cwd);if((e.installMethod??(await $o(t,`cargo`,e.cwd)?`cargo`:`official-script`))===`cargo`){let n=[`install`,`--git`,`https://github.com/rtk-ai/rtk`];if(r.push(es(`cargo`,n)),!e.dryRun){let i=await t(`cargo`,n,{cwd:e.cwd});if(i.exitCode!==0)return{status:`error`,message:`A instalação do RTK via Cargo falhou.`,details:[...a?["Já existe um executável `rtk`, mas ele não passou em `rtk gain`."]:[],i.stderr.trim()||i.stdout.trim()].filter(Boolean),commands:r}}}else if(r.push(`curl -fsSL ${Yo} -o <arquivo-temporario>`,`sh <arquivo-temporario>`),!e.dryRun){if(process.platform===`win32`)return{status:`warn`,message:`O instalador oficial exige shell Unix; use WSL ou Cargo no Windows.`,commands:r};let n=await S(s.join(w(),`rock-rtk-`)),i=s.join(n,`install.sh`);try{let n=await t(`curl`,[`-fsSL`,Yo,`-o`,i],{cwd:e.cwd});if(n.exitCode!==0)throw Error(n.stderr.trim()||`download falhou`);let r=await t(`sh`,[i],{cwd:e.cwd,shell:!1});if(r.exitCode!==0)throw Error(r.stderr.trim()||r.stdout.trim()||`instalação falhou`)}catch(e){return{status:`error`,message:`O instalador oficial do RTK falhou.`,details:[...a?["Já existe um executável `rtk`, mas ele não passou em `rtk gain`."]:[],String(e)],commands:r}}finally{await te(n,{recursive:!0,force:!0})}}if(e.dryRun)return{status:`ok`,message:`Instalação do RTK planejada.`,commands:r};let o=await Qo(t,e.cwd);return o?{status:`ok`,message:`RTK instalado e validado (${o}).`,commands:r}:{status:`error`,message:"RTK foi instalado, mas `rtk gain` não pôde ser validado.",commands:r}}async function Zo(e,t){let r=t.dependencies?.run??((e,r,i)=>n(e,r,{cwd:i?.cwd??t.cwd})),i=[],a=[];for(let n of e){let e=n===`codex`?[`init`,`--global`,`--codex`]:[`init`,`--global`];if(i.push(es(`rtk`,e)),t.dryRun)continue;let o=await r(`rtk`,e,{cwd:t.cwd});if(o.exitCode!==0)return{status:`error`,message:`Não foi possível configurar o RTK no ${n}.`,details:[o.stderr.trim()||o.stdout.trim()].filter(Boolean),commands:i};a.push(`${n} configurado`)}return{status:`ok`,message:t.dryRun?`Configuração dos agentes planejada.`:`RTK configurado nos agentes selecionados.`,details:a,commands:i}}async function Qo(e,t){try{if((await e(`rtk`,[`gain`],{cwd:t})).exitCode!==0)return;let n=await e(`rtk`,[`--version`],{cwd:t});return n.exitCode===0?`${n.stdout||n.stderr}`.trim().split(/\r?\n/,1)[0]:`versão desconhecida`}catch{return}}async function $o(e,t,n){try{return(await e(t,[`--version`],{cwd:n})).exitCode===0}catch{return!1}}function es(e,t){return[e,...t].join(` `)}const Q={diagnostics:`Diagnóstico`,skills:`Skills globais`,rtk:`Instalação do RTK`,agents:`Configuração Claude/Codex`,graph:`Code-review graph`};function ts(e){return{id:e,label:Q[e],status:`skipped`,message:`Etapa ignorada.`}}async function ns(e,n={}){let r=e.agents?.length?e.agents:[`claude-code`,`codex`],i=await Ho(e.cwd,n),a=[{id:`diagnostics`,label:Q.diagnostics,status:`ok`,message:`Diagnóstico concluído.`,details:[`Plataforma: ${i.platform}/${i.architecture}`,`Shell: ${i.shell}`,...i.tools.map(e=>`${e.name}: ${e.available?e.version??`disponível`:`não encontrado`}`),...i.configFiles.length>0?[`Configurações encontradas: ${i.configFiles.join(`, `)}`]:[`Nenhuma configuração global de agente encontrada.`]]}],o=[],s=t=>(!e.only||e.only.includes(t))&&!e.skip?.includes(t);if(s(`skills`)){let{official:i,optional:s}=(await import(`./skills-DuE-XnBp.js`)).getSetupSkills(),c=e.optionalSkillIds??(e.includeOptionalSkills?s.map(e=>e.id):[]),l=e.skillIds??c,u=[...i,...s].filter(e=>l.includes(e.id)),d=await t(u,r,{cwd:e.cwd,dryRun:e.dryRun,dependencies:n});o.push(d.command??``),a.push({id:`skills`,label:Q.skills,status:d.status,message:d.message,details:d.details})}else a.push(ts(`skills`));if(s(`rtk`)){let t=await Xo({cwd:e.cwd,dryRun:e.dryRun,installMethod:e.installMethod,dependencies:n});o.push(...t.commands),a.push({id:`rtk`,label:Q.rtk,status:t.status,message:t.message,details:t.details})}else a.push(ts(`rtk`));if(s(`agents`)){let t=a.find(e=>e.id===`rtk`);if(t?.status===`ok`||t?.status===`skipped`){let t=e.dryRun?[]:await qo({home:n.homedir?.(),now:n.now?.()}),i=await Zo(r,{cwd:e.cwd,dryRun:e.dryRun,dependencies:n});o.push(...i.commands),a.push({id:`agents`,label:Q.agents,status:i.status,message:i.message,details:[...t.length>0?[`Backup criado: ${t.join(`, `)}`]:[],...i.details??[]]})}else a.push({id:`agents`,label:Q.agents,status:`warn`,message:`Configuração ignorada porque o RTK não foi validado.`})}else a.push(ts(`agents`));if(s(`graph`)){let t=await Jo({cwd:e.cwd,dryRun:e.dryRun,dependencies:n});o.push(...t.commands),a.push({id:`graph`,label:Q.graph,status:t.status,message:t.message,details:t.details})}else a.push(ts(`graph`));return{diagnostics:i,steps:a,commands:o.filter(Boolean)}}async function rs(e,t){return e.yes?t?`cargo`:`official-script`:B(await L({message:`Como deseja instalar o RTK se ele ainda não estiver instalado?`,options:[...t?[{value:`cargo`,label:`Cargo`,hint:`Usa Rust/Cargo e o repositório oficial.`}]:[],{value:`official-script`,label:`Instalador oficial`,hint:`Baixa o instalador do repositório rtk-ai/rtk.`}]}),`Operação cancelada.`)}const is=[{value:`diagnostics`,label:`Diagnóstico`,hint:`Ferramentas, versões, permissões e configurações.`},{value:`skills`,label:`Skills globais`,hint:`Skills oficiais Rockfeller para Claude Code e Codex.`},{value:`rtk`,label:`RTK`,hint:`Instala e valida o Rust Token Killer.`},{value:`agents`,label:`Claude/Codex`,hint:`Configura o RTK nos agentes selecionados.`},{value:`graph`,label:`Code-review graph`,hint:`Atualiza o grafo local do repositório.`}];function as(e,t){return(!e.only||e.only.includes(t))&&!e.skip?.includes(t)}function os(e){return{cwd:process.cwd(),dryRun:e.dryRun,yes:e.yes,optionalSkills:e.optionalSkills,skillIds:e.skills===!1?[]:e.skills?ss(e.skills):void 0,agents:e.agents?cs(e.agents):void 0,only:e.only?ls(e.only):void 0,skip:e.skip?ls(e.skip):void 0}}function ss(e){let{official:t,optional:n}=r(),i=new Set([...t,...n].map(e=>e.id));return[...new Set(e.split(`,`).map(e=>{let t=e.trim();if(!i.has(t))throw Error(`Skill desconhecida: ${t}`);return t}))]}function cs(e){let t=e.split(`,`).map(e=>{if(e.trim()===`claude`)return`claude-code`;if(e.trim()===`codex`)return`codex`;throw Error(`Agente desconhecido: ${e}`)});if(t.length===0)throw Error(`Informe pelo menos um agente.`);return[...new Set(t)]}function ls(e){return e.split(`,`).map(e=>{let t=e.trim();if(!is.some(e=>e.value===t))throw Error(`Etapa desconhecida: ${e}`);return t})}function us(e,t){t?console.log(JSON.stringify(e,null,2)):ds(e)}function ds(e){console.log(``),console.log(z.default.bold(`Resumo do setup`));for(let t of e.steps){let e=t.status===`ok`?z.default.green(`OK`):t.status===`warn`?z.default.yellow(`WARN`):t.status===`error`?z.default.red(`ERROR`):z.default.dim(`SKIP`);console.log(`${e} ${t.label}: ${t.message}`);for(let e of t.details??[])console.log(` ${z.default.dim(`-`)} ${e}`)}if(e.commands.length>0){console.log(``),console.log(z.default.bold(`Comandos executados ou planejados`));for(let t of e.commands)console.log(` ${z.default.dim(`$`)} ${t}`)}let t=e.steps.filter(e=>e.status===`error`).length;console.log(``),F(t===0?z.default.green(`Setup concluído. Reinicie Claude Code e Codex para aplicar as alterações.`):z.default.yellow(`Setup concluído com falhas; revise os comandos e avisos acima.`)),t>0&&(process.exitCode=1)}function fs(e){e.command(`setup`).description(`Prepara globalmente o ambiente para Claude Code e Codex`).option(`--yes`,`Executa sem prompts interativos`).option(`--dry-run`,`Mostra o que seria feito sem modificar o computador`).option(`--agents <agents>`,`Agentes separados por vírgula: claude,codex`).option(`--only <steps>`,`Executa apenas etapas separadas por vírgula`).option(`--skip <steps>`,`Ignora etapas separadas por vírgula`).option(`--skills <ids>`,`Instala somente as skills selecionadas, separadas por virgula`).option(`--no-skills`,`Continua sem instalar nenhuma skill`).option(`--no-optional-skills`,`Não oferece skills de terceiros`).option(`--json`,`Emite o relatório em JSON`).action(async e=>{let t=os(e);if(e.json||e.yes||e.dryRun){us(await ns({...t,skillIds:t.skillIds??[]}),!!e.json);return}let{official:n,optional:i}=r();I([z.default.bold(`O setup global vai preparar seu ambiente.`),``,`• Todas as skills são opcionais; nenhuma vem selecionada.`,`• O RTK será instalado e configurado nos agentes selecionados.`,`• Configurações existentes serão preservadas e terão backup antes da alteração.`,`• O code-review graph é opcional e pode demorar alguns minutos.`].join(`
|
|
1218
|
-
`),`rock setup`);let a=t.agents??B(await P({message:`Quais agentes deseja configurar?`,initialValues:[`claude-code`,`codex`],options:[{value:`claude-code`,label:`Claude Code`,hint:`Skills globais e RTK.`},{value:`codex`,label:`Codex`,hint:`Skills globais e RTK.`}]}),`Operação cancelada.`);if(a.length===0)throw Error(`Selecione pelo menos um agente.`);let o=[...n,...e.optionalSkills===!1?[]:i],s=t.skillIds??(as(t,`skills`)?B(await P({message:`Quais skills deseja instalar? (opcional)`,required:!1,initialValues:[],options:o.map(e=>({value:e.id,label:e.label,hint:e.description}))}),`Operação cancelada.`):[]),c=as(t,`rtk`)?await rs(t,await Uo(`cargo`,t.cwd)):void 0,l=as(t,`graph`),u=l?B(await Rt({message:`Deseja atualizar o code-review graph deste repositório?`,initialValue:!1}),`Operação cancelada.`):!1;ds(await ns({...t,agents:a,skillIds:s,installMethod:c,skip:u||!l?t.skip:[...t.skip??[],`graph`]}))})}async function ps(e){let t=s.join(e,`.github`,`workflows`);try{let e=(await ee(t,{withFileTypes:!0})).filter(e=>e.isFile()).map(e=>e.name).sort();return e.length===0?{id:`ci`,label:`CI`,level:`warn`,message:`Diretorio .github/workflows existe, mas sem workflows.`}:{id:`ci`,label:`CI`,level:`ok`,message:`Workflows encontrados.`,details:e.map(e=>`.github/workflows/${e}`)}}catch(e){if(e.code===`ENOENT`)return{id:`ci`,label:`CI`,level:`warn`,message:`Nenhum workflow de CI encontrado.`};throw e}}function ms(e){return typeof e==`string`?`bin: ${e}`:`bin: ${Object.entries(e??{}).map(([e,t])=>`${e} -> ${t}`).join(`, `)}`}async function hs(e){try{let t=await C(s.join(e,`package.json`),`utf8`);return JSON.parse(t)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function gs(e){return e?.split(`@`)[0]}async function _s(e){let t=await hs(e);return t?t.name?t.bin?{id:`package`,label:`Package metadata`,level:`ok`,message:`Pacote ${t.name} com bin configurado.`,details:[ms(t.bin)]}:{id:`package`,label:`Package metadata`,level:`ok`,message:`Pacote ${t.name} configurado.`}:{id:`package`,label:`Package metadata`,level:`warn`,message:`package.json sem campo name.`}:{id:`package`,label:`Package metadata`,level:`error`,message:`package.json nao encontrado.`}}const vs={bun:[`bun.lock`,`bun.lockb`],pnpm:[`pnpm-lock.yaml`],npm:[`package-lock.json`],yarn:[`yarn.lock`]},ys=Object.values(vs).flat(),bs=[`vercel.json`,`render.yaml`,`railway.json`,`fly.toml`,`netlify.toml`,`wrangler.toml`,`Procfile`];async function xs(e,t){return(await Promise.all(t.map(async t=>await Ss(s.join(e,t))?t:null))).filter(e=>e!==null)}async function $(e,t){for(let n of t)if(await Ss(s.join(e,n)))return n}async function Ss(e){try{return await y(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function Cs(e){let t=await xs(e,bs),n=await $(e,[`.github/workflows/release.yml`,`.github/workflows/release.yaml`,`.github/workflows/release-publish.yml`,`.github/workflows/release-publish.yaml`,`.github/workflows/deploy.yml`,`.github/workflows/deploy.yaml`,`.github/workflows/publish.yml`,`.github/workflows/publish.yaml`]),r=await hs(e),i=r?.private===!1&&r.publishConfig?.access===`public`;return t.length===0&&!n&&!i?{id:`deploy`,label:`Deploy/Publish`,level:`warn`,message:`Nenhuma configuracao clara de deploy ou publish foi encontrada.`}:{id:`deploy`,label:`Deploy/Publish`,level:`ok`,message:`Existe pelo menos um caminho de deploy ou publish configurado.`,details:[...t,...n?[n]:[],...i?[`package.json publishConfig publico`]:[]]}}async function ws(e){let t=await $(e,[`Dockerfile`,`dockerfile`]);if(!t)return{id:`dockerfile`,label:`Dockerfile`,level:`warn`,message:`Dockerfile nao encontrado.`};let n=(await C(s.join(e,t),`utf8`)).toLowerCase(),r=n.includes(`from `),i=n.includes(`workdir `),a=n.includes(`cmd `)||n.includes(`entrypoint `);return r&&i&&a?{id:`dockerfile`,label:`Dockerfile`,level:`ok`,message:`${t} parece completo para build/run.`}:{id:`dockerfile`,label:`Dockerfile`,level:`warn`,message:`${t} existe, mas parece incompleto.`,details:[`FROM: ${r?`ok`:`faltando`}`,`WORKDIR: ${i?`ok`:`faltando`}`,`CMD/ENTRYPOINT: ${a?`ok`:`faltando`}`]}}async function Ts(e){let t=await $(e,[`.env`]),n=await $(e,[`.env.example`]);if(!t&&!n)return{id:`env`,label:`.env.example`,level:`warn`,message:`Nem .env nem .env.example foram encontrados.`};if(t&&!n)return{id:`env`,label:`.env.example`,level:`warn`,message:`.env existe, mas .env.example nao foi encontrado.`};if(!t&&n)return{id:`env`,label:`.env.example`,level:`ok`,message:`.env.example existe; .env local nao esta presente para comparar.`};if(!t||!n)return{id:`env`,label:`.env.example`,level:`warn`,message:`Nao foi possivel comparar .env com .env.example.`};let[r,i]=await Promise.all([C(s.join(e,t),`utf8`),C(s.join(e,n),`utf8`)]),a=En(r),o=En(i),c=a.filter(e=>!o.includes(e)),l=o.filter(e=>!a.includes(e));if(c.length===0&&l.length===0)return{id:`env`,label:`.env.example`,level:`ok`,message:`.env.example esta alinhado com .env.`,details:[`Variaveis comparadas: ${a.length}`]};let u=[];return c.length>0&&u.push(`Faltando no .env.example: ${c.join(`, `)}`),l.length>0&&u.push(`Sobrando no .env.example: ${l.join(`, `)}`),{id:`env`,label:`.env.example`,level:`warn`,message:`.env.example precisa ser sincronizado com .env.`,details:u}}async function Es(e){return await $(e,[`.git`])?{id:`git`,label:`Git`,level:`ok`,message:`Repositorio Git inicializado.`}:{id:`git`,label:`Git`,level:`warn`,message:`Diretorio .git nao encontrado.`}}async function Ds(e){return await $(e,[`.gitignore`])?{id:`gitignore`,label:`.gitignore`,level:`ok`,message:`.gitignore encontrado.`}:{id:`gitignore`,label:`.gitignore`,level:`warn`,message:`.gitignore nao encontrado.`}}async function Os(e){let t=await hs(e);if(!t)return{id:`package-manager`,label:`Package manager`,level:`error`,message:`package.json nao encontrado.`};let n=gs(t.packageManager),r=await xs(e,ys);if(!n)return{id:`package-manager`,label:`Package manager`,level:`warn`,message:`package.json sem campo packageManager.`,details:r.length?[`Lockfiles encontrados: ${r.join(`, `)}`]:[`Nenhum lockfile encontrado.`]};let i=vs[n]??[],a=i.some(e=>r.includes(e)),o=r.some(e=>!i.includes(e));return a?o?{id:`package-manager`,label:`Package manager`,level:`warn`,message:`packageManager e lockfile principal batem (${n}), mas existem lockfiles extras.`,details:[`Lockfiles encontrados: ${r.join(`, `)}`]}:{id:`package-manager`,label:`Package manager`,level:`ok`,message:`packageManager e lockfile estao alinhados em ${n}.`,details:[`Lockfile: ${r.join(`, `)}`]}:{id:`package-manager`,label:`Package manager`,level:`error`,message:`packageManager declara ${n}, mas o lockfile correspondente nao existe.`,details:r.length?[`Lockfiles encontrados: ${r.join(`, `)}`]:[`Esperado: ${i.join(` ou `)}`]}}async function ks(e){let t=await $(e,[`README.md`,`README.mdx`,`README`]);return t?{id:`readme`,label:`README`,level:`ok`,message:`Arquivo encontrado: ${t}.`}:{id:`readme`,label:`README`,level:`error`,message:`README nao encontrado.`}}async function As(e){let t=await hs(e);if(!t)return{id:`scripts`,label:`Scripts`,level:`error`,message:`package.json nao encontrado.`};let n=[`lint`,`typecheck`,`test`,`build`],r=t.scripts??{},i=n.filter(e=>!r[e]);return i.length===0?{id:`scripts`,label:`Scripts`,level:`ok`,message:`Scripts principais de qualidade estao presentes.`,details:n.map(e=>`${e}: ${r[e]}`)}:{id:`scripts`,label:`Scripts`,level:`warn`,message:`Faltam scripts recomendados de qualidade.`,details:[`Faltando: ${i.join(`, `)}`]}}async function js(e=process.cwd()){let t=await Promise.all([Os(e),ks(e),ps(e),Ts(e),ws(e),Cs(e),As(e),Ds(e),Es(e),_s(e)]);return{rootDir:e,checks:t,counts:t.reduce((e,t)=>(e[t.level]+=1,e),{ok:0,warn:0,error:0})}}function Ms(e){e.command(`status`).description(`Mostra um status geral da configuracao do projeto atual`).action(async()=>{let e=await js(process.cwd());console.log(z.default.bold(`Status do projeto: ${e.rootDir}`)),console.log(``);for(let t of e.checks){console.log(Ns(t));for(let e of t.details??[])console.log(` ${z.default.dim(`-`)} ${e}`)}console.log(``),console.log([`${z.default.green(`${e.counts.ok} ok`)}`,`${z.default.yellow(`${e.counts.warn} avisos`)}`,`${z.default.red(`${e.counts.error} erros`)}`].join(` `)),e.counts.error>0&&(process.exitCode=1)})}function Ns(e){return`${e.level===`ok`?z.default.green(`OK`):e.level===`warn`?z.default.yellow(`WARN`):z.default.red(`ERROR`)} ${z.default.bold(e.label)}: ${e.message}`}function Ps(){let e=process.env.XDG_CONFIG_HOME??process.env.APPDATA??s.join(ae(),`.config`);return s.join(e,`rock`,`updates.json`)}async function Fs(e){try{let t=await(e?.readFile??C)(e?.filePath??Ps(),`utf8`),n=JSON.parse(t);return typeof n.skippedVersion==`string`?n.skippedVersion:void 0}catch{return}}async function Is(e,t){try{let n=t?.filePath??Ps();await(t?.mkdir??x)(s.dirname(n),{recursive:!0}),await(t?.writeFile??re)(n,`${JSON.stringify({skippedVersion:e})}\n`,`utf8`)}catch{}}function Ls(e){let t=/^v?(\d+)\.(\d+)\.(\d+)$/.exec(e.trim());if(t)return t.slice(1).map(Number)}function Rs(e,t){let n=Ls(e),r=Ls(t);if(!n||!r)return!1;for(let[e,t]of n.entries())if(t!==r[e])return t>(r[e]??0);return!1}async function zs(e,t,n,r){try{let i=await t(e,{headers:n,signal:AbortSignal.timeout(r)});return i.ok?i.json():void 0}catch{return}}async function Bs(e){let t=e?.fetch??globalThis.fetch,n=e?.timeoutMs??750,r=await zs(`https://api.github.com/repos/rockfellerfranchising/npm/releases/latest`,t,{Accept:`application/vnd.github+json`},n),i=typeof r?.tag_name==`string`?r.tag_name.replace(/^v/,``):void 0;if(i&&Ls(i))return{version:i};let a=await zs(`https://registry.npmjs.org/franchising/latest`,t,{Accept:`application/json`},n),o=typeof a?.version==`string`?a.version:void 0;return o&&Ls(o)?{version:o}:void 0}function Vs(e=ie(import.meta.url)){let t=e.replaceAll(`\\`,`/`);return t.includes(`/.bun/install/global/node_modules/`)?`bun`:t.includes(`/pnpm/global/`)||t.includes(`/node_modules/.pnpm/`)?`pnpm`:t.includes(`/yarn/global/node_modules/`)?`yarn`:`npm`}async function Hs(e,t){let n=t?.run??((e,t)=>R(e,t,{cwd:process.cwd()})),r=t?.packageManager??Vs(),i=`franchising@${e}`;r===`bun`?await n(`bun`,[`install`,`--global`,i]):r===`pnpm`?await n(`pnpm`,[`add`,`--global`,i]):r===`yarn`?await n(`yarn`,[`global`,`add`,i]):await n(`npm`,[`install`,`--global`,i])}function Us(e=process.env,t=!!(process.stdin.isTTY&&process.stdout.isTTY)){return e.CI||e.ROCK_NO_UPDATE_CHECK?!1:t}async function Ws(e,t={getLatestRelease:Bs,getSkippedUpdateVersion:Fs,select:L,skipUpdateUntilNextRelease:Is,updateCli:Hs}){let n=await t.getLatestRelease();if(!n||!Rs(n.version,e))return`up-to-date`;if(await t.getSkippedUpdateVersion()===n.version)return`skipped-version`;let r=await t.select({message:`Nova versao ${n.version} disponivel. Deseja atualizar agora?`,options:[{value:`install`,label:`Instalar nova versao`},{value:`skip`,label:`Pular`},{value:`skip-until-next-update`,label:`Pular ate a proxima atualizacao`}]});return r===`skip-until-next-update`?(await t.skipUpdateUntilNextRelease(n.version),`skipped-version`):r!==`install`||rt(r)?`skipped`:(await t.updateCli(n.version),F(`Rock atualizado para a versao ${n.version}.`),`updated`)}function Gs(e,t){e.command(`update`).alias(`upgrade`).description(`Atualiza a CLI para a ultima release disponivel`).action(async()=>{let e=await Bs();if(!e)throw Error(`Nao foi possivel consultar as releases do GitHub.`);Rs(e.version,t)?(await Hs(e.version),F(`Rock atualizado para a versao ${e.version}.`)):F(`Voce ja esta na versao mais recente (${t}).`)})}function Ks(){let e=new Ee;return e.name(`rock`).version(ke).description(`CLI to generate a scaffold for Rockfeller projects`),jn(e),yn(e),Bo(e),Ms(e),fs(e),Gs(e,ke),e.hook(`preAction`,async(e,t)=>{Us()&&![`update`,`setup`].includes(t.name())&&await Ws(ke)}),e}await Ks().parseAsync(process.argv);export{};
|
|
1531
|
+
`},{path:`.gitignore`,content:rr({outputEntries:[`.next`],cacheEntries:[`.vercel`]})},...Sa({hasWeb:!0,hasApi:!1,editorconfig:e.features.editorconfig,lefthook:e.features.lefthook,ultracite:e.features.ultracite,commitlint:e.features.commitlint,dockerignore:e.features.dockerignore,packageManager:e.packageManager}),{path:`commitlint.config.ts`,content:ir(),condition:e=>e.features.commitlint},{path:`Dockerfile`,content:``,condition:e=>e.features.dockerfile},...Ua({packageManager:e.packageManager,workflows:e.workflows})]}},Qa];function is(){let e={monolith:`Monolito Modular`,api:`API`,web:`Web`};return rs.map(t=>({value:t.id,label:e[t.id],hint:t.description}))}function as(e){return rs.find(t=>t.id===e)}async function os(e,t){try{await I(t,[`run`,`format`],{cwd:e})}catch{return!1}return!0}async function ss(e){try{await I(`git`,[`init`,`--initial-branch=main`],{cwd:e})}catch{await I(`git`,[`init`],{cwd:e}),await I(`git`,[`symbolic-ref`,`HEAD`,`refs/heads/main`],{cwd:e})}}async function cs(e){let t=as(e.templateId),n=Qn({runtime:e.runtime,packageManager:e.packageManager,templateId:e.templateId,apiHosting:e.hosting?.api});if(n)throw Error(n);if(!t)throw Error(`Template desconhecido: ${e.templateId}`);let r=t.createContext({hosting:e.hosting,name:e.name,packageManager:e.packageManager,runtime:e.runtime,fullSetup:e.fullSetup,setupFeatures:e.setupFeatures,authProviders:e.authProviders,authPlugins:e.authPlugins,telemetryAdapter:e.telemetryAdapter,workers:e.workers,messaging:e.messaging,implementAuthModule:e.implementAuthModule,databaseOrm:e.databaseOrm,workflows:e.workflows}),i=c.resolve(e.cwd,e.name);await Rn(i),await zn(i,Ni(di(ui(ji(oi(Mi(Vr(t.files(r).filter(e=>!e.condition||e.condition(r)),r,e.templateId)),r),r,e.templateId)),e.envValues))),await ss(i);let a=!1;e.installDependencies&&(await Pi(i,e.packageManager,{lefthook:r.features.lefthook}),a=await os(i,e.packageManager));let o=[...a?[]:[`${e.packageManager} run format`],e.installDependencies?`${e.packageManager} run dev`:`${e.packageManager===`pnpm`?`pnpm install && `:`bun install && `}${e.packageManager} run dev`,...(t.postCreateSteps?.(r)??[]).filter(t=>!e.installDependencies||!t.includes(`lefthook install`))];return{targetDir:i,projectDirectoryName:c.basename(i),nextSteps:o}}const ls={R:[`####.`,`#...#`,`####.`,`#..#.`,`#...#`],O:[`.###.`,`#...#`,`#...#`,`#...#`,`.###.`],C:[`.####`,`#....`,`#....`,`#....`,`.####`],K:[`#...#`,`#..#.`,`###..`,`#..#.`,`#...#`],F:[`#####`,`#....`,`####.`,`#....`,`#....`],E:[`#####`,`#....`,`####.`,`#....`,`#####`],L:[`#....`,`#....`,`#....`,`#....`,`#####`]};function us(e){return!(e.yes||!e.isTTY||e.env.CI)}function ds(e){let t=[...e].map(e=>ls[e]??[]),n=t.length>0?5:0,r=t.length*6,i=Array.from({length:n+1},()=>Array.from({length:r+1},()=>` `));for(let[e,n]of t.entries())for(let[t,r]of n.entries())for(let[n,a]of[...r].entries())if(a===`#`){let r=e*6+n;i[t][r]=`#`,i[t+1][r+1]===` `&&(i[t+1][r+1]=`~`)}return i}function fs(e,t,n,r){if(!L.default.isColorSupported)return e;let i=n>1?t/(n-1):0,[a,o,s]=r?[150,120,20]:[255,Math.round(204+51*i),Math.round(255*i)];return`\u001B[38;2;${a};${o};${s}m${e}\u001B[39m`}function ps(e){let t=ds(e),n=(t[0]?.length??1)-1;return t.map(e=>e.map((e,t)=>e===`#`?fs(`█`,t,n,!1):e===`~`?fs(`░`,t,n,!0):` `).join(``).trimEnd())}function ms(e){return ps(e<64?`ROCK`:`ROCKFELLER`).join(`
|
|
1532
|
+
`)}const hs=`rockfellerfranchising`;function gs(e){return`https://github.com/${hs}/${e}`}function _s(e){return`gh repo create ${hs}/${e} --private --source . --push`}function vs(e){let t=c.join(e,`docker-compose.yml`);return u(t)?[...(/^services:\n((?:[ \t].*\n?|\n)*)/m.exec(d(t,`utf8`))?.[1]??``).matchAll(/^ {2}([\w.-]+):/gm)].map(e=>e[1]):[]}function ys(e){let t=e===`api`?[]:[[`Web`,`http://localhost:3000`]],n=e===`web`?[]:[[`API`,`http://localhost:3001`],[`Docs da API`,`http://localhost:3001/v1/docs`]];return[...t,...n]}function bs(e,t){return t.length>0?[``,L.default.bold(L.default.yellow(e)),...t]:[]}const xs=e=>`${L.default.yellow(`•`)} ${e}`;function Ss(e){return[L.default.bold(L.default.green(`Projeto gerado.`)),`${L.default.dim(`Pasta:`)} ${e.targetDir}`,...bs(`Próximos comandos`,[L.default.cyan(`cd ${e.projectDirectoryName}`),...e.nextSteps.map(e=>L.default.cyan(e))]),...bs(`Rodando localmente`,ys(e.templateId).map(([e,t])=>xs(`${e}: ${L.default.underline(t)}`))),...bs(`Serviços do Docker Compose`,e.composeServices.length>0?[e.composeServices.map(xs).join(` `)]:[]),...bs(`Skills`,[...e.installedSkills.length>0?[e.installedSkills.map(xs).join(` `)]:[],...e.skillCommands.length>0?[L.default.dim(`Falharam; tente de novo com:`),...e.skillCommands]:[]]),``,`${L.default.bold(`Bora pro GitHub?`)} ${L.default.dim(`Crie o repositório na organização`)}`,L.default.cyan(gs(e.slug)),L.default.dim(_s(e.slug))].join(`
|
|
1533
|
+
`)}const Cs=[{id:`zed`,label:`Zed`,command:[`zed`,`.`]},{id:`codex`,label:`Codex CLI`,command:[`codex`]},{id:`claude`,label:`Claude Code`,hint:`agente de código`,command:[`claude`]},{id:`cursorAgent`,label:`Cursor Agent`,command:[`cursor-agent`]},{id:`orca`,label:`Orca`,command:[`orca`,`.`]},{id:`vscode`,label:`VS Code`,command:[`code`,`.`]},{id:`cursor`,label:`Cursor IDE`,command:[`cursor`,`.`]},{id:`github`,label:`Criar repositório no GitHub agora`,hint:`usa o gh`},{id:`none`,label:`Agora não`}],ws={spawn:(e,t,n)=>s(e,t,n),warn:e=>console.warn(e)};function Ts(e,t,n){let r=n.spawn(`gh`,[`auth`,`status`],{cwd:e,stdio:`ignore`});return r.error||r.status!==0?(n.warn("gh não encontrado ou sem login. Rode `gh auth login` e depois o comando da tela acima."),!1):n.spawn(`gh`,[`repo`,`create`,`${hs}/${t}`,`--private`,`--source`,`.`,`--push`],{cwd:e,stdio:`inherit`}).status===0}function Es(e,t,n,r=ws){if(e===`none`)return!0;if(e===`github`)return Ts(t,n,r);let i=Cs.find(t=>t.id===e);if(!i?.command)return!1;let[a,...o]=i.command;return!r.spawn(a,o,{cwd:t,stdio:`inherit`,shell:process.platform===`win32`}).error||(r.warn(`Não consegui abrir com ${i.label}: \`${a}\` não está no PATH.`),!1)}async function Ds(e,t){let n=await F({message:`Abrir o projeto com?`,initialValue:`claude`,options:Cs.map(e=>({value:e.id,label:e.label,...e.hint?{hint:e.hint}:{}}))});typeof n!=`symbol`&&Es(n,e,t)}function Os(e,t,n,r){let i=e.options?.[t],a={apiHosting:`--api-hosting`,webHosting:`--web-hosting`,webType:`--web-type`}[t];if(i!==void 0&&!n.includes(i))throw Error(`Valor invalido para ${a}: use ${n.join(`, `)}.`);if(i!==void 0&&(t===`apiHosting`&&r.templateId===`web`||t!==`apiHosting`&&r.templateId===`api`))throw Error(`${a} nao se aplica ao template ${r.templateId}.`);if(e.options?.serverless&&t!==`webType`&&i!==void 0&&i!==`cloudflare`)throw Error(`Conflito: --serverless exige ${a} cloudflare.`);return i}const ks=[`vinext`,`opennext`],As=[{id:`apiHosting`,fromArgs:(e,t)=>{let n=Os(e,`apiHosting`,[`traditional`,`railway`,`cloudflare`],t)??(e.options?.serverless&&t.templateId!==`web`?`cloudflare`:void 0),r=Qn({runtime:t.runtime,apiHosting:n});if(r)throw Error(r);return t.runtime===`bun`?n??`traditional`:n},when:e=>e.templateId!==`web`,defaultValue:()=>`traditional`,label:`Hospedagem da API`,prompt:(e,t)=>F({message:`Deseja usar Serverless na API?`,initialValue:t??`traditional`,options:[{value:`traditional`,label:`Nao, manter servidor tradicional`},{value:`cloudflare`,label:`Sim, Cloudflare Workers`}]}),summary:e=>e?`Hospedagem API: ${e}`:void 0},{id:`webType`,fromArgs:(e,t)=>Os(e,`webType`,[`application`,`landing`],t),when:e=>e.templateId!==`api`,defaultValue:()=>`application`,label:`Tipo de website`,prompt:(e,t)=>F({message:`Qual tipo de website deseja gerar?`,initialValue:t??`application`,options:[{value:`application`,label:`Aplicacao com servidor (login/dashboard opcionais)`},{value:`landing`,label:`Landing page estatica`}]}),summary:e=>e?`Website: ${e}`:void 0},{id:`webHosting`,fromArgs:(e,t)=>Os(e,`webHosting`,[`traditional`,`vercel`,`cloudflare`],t)??(e.options?.serverless&&t.templateId!==`api`?`cloudflare`:void 0),when:e=>e.templateId!==`api`,defaultValue:()=>`traditional`,label:`Hospedagem do website`,prompt:(e,t)=>F({message:`Deseja hospedar o website no Cloudflare?`,initialValue:t??`traditional`,options:[{value:`traditional`,label:`Nao, manter hospedagem tradicional`},{value:`cloudflare`,label:`Sim, Cloudflare`}]}),summary:e=>e?`Hospedagem web: ${e}`:void 0},{id:`webAdapter`,fromArgs:(e,t)=>{let n=e.options?.webAdapter;if(n!==void 0){if(!ks.includes(n))throw Error(`Valor invalido para --web-adapter: use ${ks.join(`, `)}.`);if(t.webHosting!==`cloudflare`)throw Error(`--web-adapter exige website no Cloudflare.`);return n}},when:e=>e.webHosting===`cloudflare`,defaultValue:()=>`vinext`,label:`Adapter web`,prompt:(e,t)=>F({message:`Qual adapter deseja usar no Cloudflare?`,initialValue:t??`vinext`,options:e.webType===`landing`?[{value:`vinext`,label:`vinext (Workers estatico)`},{value:`opennext`,label:`Pages estatico (legado)`}]:[{value:`vinext`,label:`vinext (Vite, recomendado)`},{value:`opennext`,label:`OpenNext (mais maduro)`}]}),summary:e=>e?`Adapter web: ${e}`:void 0},{id:`kv`,fromArgs:(e,t)=>{if(e.options?.kv&&t.apiHosting!==`cloudflare`)throw Error(`--kv exige API no Cloudflare.`);return e.options?.kv},when:e=>e.apiHosting===`cloudflare`,fallback:!1,defaultValue:()=>!1,label:`Cache KV`,prompt:(e,t)=>F({message:`Deseja usar cache Cloudflare KV?`,initialValue:t??!1,options:[{value:!1,label:`Nao`},{value:!0,label:`Sim, cache KV`}]})}];function js(e){if(e.webType===`landing`&&e.setupFeatures?.includes(`betterAuth`)&&(e.webType=`application`),e.apiHosting===`railway`)for(let t of[`railway`,`dockerfile`])e.setupFeatures.includes(t)||e.setupFeatures.push(t);return e.webHosting===`vercel`&&!e.setupFeatures.includes(`vercel`)&&e.setupFeatures.push(`vercel`),e}const Ms={templateId:`o template (rock new <web|api|monolith> <nome> --yes)`,projectName:`o nome (rock new <template> <nome> --yes)`};function Ns(e){return Array.isArray(e)?e.length>0?e.map(e=>typeof e==`object`&&e&&`name`in e?String(e.name):String(e)).join(`, `):`nenhum`:typeof e==`boolean`?e?`sim`:`não`:e===void 0?``:String(e)}async function Ps(e,t,n){let r=R(await F({message:`Revise as respostas. Deseja alterar alguma?`,initialValue:-1,options:[{value:-1,label:`Tudo certo, gerar o projeto`},...t.map(t=>{let r=e[t],i=n[r.id];return{value:t,label:`Alterar: ${r.label??r.id}`,hint:r.review?.(i)??Ns(i)}})]}),`Operacao cancelada.`);return r===-1?void 0:r}async function Fs(e,t,n=Ps){let r={},i={},a=[],o=0;for(;;){for(let n=o;n<e.length;n++){let o=e[n],s=await o.fromArgs?.(t,r);if(s!==void 0)r[o.id]=s;else if(o.when&&!await o.when(r))o.fallback!==void 0&&(r[o.id]=o.fallback);else if(t.options?.yes){if(!o.defaultValue)throw Error(`Com --yes, informe ${Ms[o.id]??o.id}.`);r[o.id]=o.defaultValue(r)}else r[o.id]=R(await o.prompt(r,i[o.id]),`Operacao cancelada.`),a.push(n)}if(t.options?.yes||a.length===0)break;let s=await n(e,a,r);if(s===void 0)break;for(let t of e.slice(s))r[t.id]!==void 0&&(i[t.id]=r[t.id]),delete r[t.id];a=a.filter(e=>e<s),o=s}return r.apiHosting!==void 0||r.webHosting!==void 0?js(r):r}function Is(e,t){return e.map(e=>e.summary?.(t[e.id],t)).filter(e=>!!e)}function Ls(e){let{answers:t,result:n,installedSkills:r,skillCommands:i,steps:a}=e;P([...Is(a,t),`${L.default.green(`Git:`)} repositorio criado na branch main`].join(`
|
|
1534
|
+
`),L.default.bold(`Scaffold pronto`)),Gt(Ss({slug:n.projectDirectoryName,templateId:t.templateId,targetDir:n.targetDir,projectDirectoryName:n.projectDirectoryName,nextSteps:n.nextSteps,composeServices:vs(n.targetDir),installedSkills:r,skillCommands:i}))}function Rs(e){if(e.exitCode!==0)return[];try{return JSON.parse(e.stdout).map(e=>e.name?e.name.toLowerCase():e.path?.split(/[\\/]/).filter(Boolean).at(-1)?.toLowerCase()??``)}catch{return[]}}async function zs(e,t,r=n){let i=await Promise.all([[`list`,`--json`],[`list`,`--global`,`--json`]].map(async e=>{try{return Rs(await r(`npx`,[`--yes`,`skills`,...e],{cwd:t}))}catch{return[]}})),a=new Set(i.flat());return e.filter(e=>!a.has(e.skill.toLowerCase()))}function Bs(e){return ka(e.templateId).filter(t=>t.id===`railway`&&e.apiHosting===`cloudflare`||t.id===`vercel`&&e.webHosting===`cloudflare`?!1:t.id===`dockerfile`||t.id===`dockerignore`?e.templateId!==`web`&&e.apiHosting!==`cloudflare`||e.templateId===`web`&&e.webHosting!==`cloudflare`:t.id!==`dockerCompose`||e.templateId!==`web`||e.webHosting!==`cloudflare`)}function Vs(){return[{id:`setupFeatures`,defaultValue:e=>Bs(e).filter(e=>e.defaultSelected).map(e=>e.id),label:`Extras de scaffold`,prompt:(e,t)=>{let n=Bs(e);return N({message:`Quais extras de scaffold voce quer incluir?`,initialValues:t??n.filter(e=>e.defaultSelected).map(e=>e.id),options:n.map(e=>({value:e.id,label:e.label,hint:e.hint}))})},summary:e=>`${L.default.green(`Extras:`)} ${e.length>0?e.join(`, `):`nenhum`}`}]}function Hs(e){return e?.clientId&&e.clientSecret?`credenciais no .env`:`preencha ROCKFELLER_CLIENT_ID e ROCKFELLER_CLIENT_SECRET no .env`}function Q(e){return e===`api`||e===`monolith`}function Us(e,t,n){if(t!==void 0){if(!n.includes(t))throw Error(`Valor invalido para ${e}: ${L.default.yellow(t)} (use ${n.join(` ou `)}).`);return t}}function $(e){return e}const Ws=[{value:`emailAndPassword`,label:`Email e senha`,hint:`Login tradicional com credenciais.`},{value:`google`,label:`Google`,hint:`OAuth com Google.`},{value:`github`,label:`GitHub`,hint:`OAuth com GitHub.`},{value:`discord`,label:`Discord`,hint:`OAuth com Discord.`}],Gs=[{value:`quality`,label:`Verificações de qualidade`,hint:`Executa lint, verificação de tipos, testes e build em cada push e pull request.`},{value:`codeql`,label:`Análise de segurança (CodeQL)`,hint:`Procura vulnerabilidades no código JavaScript e TypeScript.`},{value:`dependencyReview`,label:`Revisão de dependências`,hint:`Verifica alterações e possíveis riscos nas dependências de cada pull request.`}],Ks=[`pnpm`,`bun`],qs=[`prisma`,`drizzle`];function Js(e){if(!e?.trim())return`Informe um nome de projeto.`;if(/[<>:"/\\|?*\x00-\x1F]/.test(e))return`Use um nome de pasta valido.`}function Ys(e){let t=/* @__PURE__ */ new Set;return e.split(`,`).map(e=>Yn(e)).filter(e=>!e||t.has(e)?!1:(t.add(e),!0)).map(e=>({name:e,queue:e}))}const Xs={emails:{name:`emails`,queue:`emails`,kind:`messaging`},webhooks:{name:`webhooks`,queue:`webhooks`,kind:`webhooks`},generic:{name:`jobs`,queue:`jobs`}},Zs=Object.keys(Xs);function Qs(e){return Zs.filter(t=>e.includes(t)).map(e=>Xs[e])}function $s(e){let t=e.split(`,`).map(e=>e.trim().toLowerCase()).filter(Boolean),n=t.filter(e=>!Zs.includes(e));if(n.length>0)throw Error(`Worker desconhecido em --workers: ${n.join(`, `)}. Use ${Zs.join(`, `)}.`);return Qs(t)}function ec(e){return Zs.find(t=>Xs[t].name===e.name)}const tc=[$({id:`templateId`,fromArgs:e=>{if(e.template){if(!as(e.template))throw Error(`Template desconhecido: ${L.default.yellow(e.template)}`);return e.template}},label:`Template`,prompt:(e,t)=>F({message:`Qual base você quer gerar?`,...t===void 0?{}:{initialValue:t},options:is()}),summary:e=>`${L.default.green(`Template:`)} ${e}`}),$({id:`projectName`,fromArgs:e=>{let t=e.name??e.options?.name,n=t===void 0?void 0:Js(t);if(n)throw Error(n);return t},label:`Nome do projeto`,prompt:(e,t)=>$t({message:`Qual será o nome do projeto? (O nome será também o da pasta dele)`,placeholder:`my-rock-app`,...t===void 0?{}:{initialValue:t},validate:Js})}),$({id:`runtime`,fromArgs:(e,t)=>{let n=Us(`--runtime`,e.options?.runtime,Zn),r=Qn({runtime:n,templateId:t.templateId});if(r)throw Error(r);return n},when:e=>Q(e.templateId),fallback:`node`,defaultValue:()=>`node`,label:`Runtime`,prompt:(e,t)=>F({message:`Em qual runtime a API e os workers vão rodar?`,initialValue:t??`node`,options:[{value:`node`,label:`Node.js`,hint:`default · pnpm ou bun`},{value:`bun`,label:`Bun`,hint:`roda o TypeScript direto; usa o Bun como package manager`}]}),summary:(e,t)=>Q(t.templateId)?`${L.default.green(`Runtime:`)} ${e}`:void 0}),$({id:`packageManager`,fromArgs:(e,t)=>{let n=Us(`--package-manager`,e.options?.packageManager,Ks),r=Qn({runtime:t.runtime,packageManager:n});if(r)throw Error(r);return n},when:e=>e.runtime!==`bun`,fallback:`bun`,defaultValue:()=>`pnpm`,label:`Package manager`,prompt:(e,t)=>F({message:`Qual package manager deseja usar?`,initialValue:t??`pnpm`,options:[{value:`pnpm`,label:`pnpm`,hint:`default`},{value:`bun`,label:`bun`}]}),summary:e=>`${L.default.green(`Package manager:`)} ${e}`}),...As,$({id:`databaseOrm`,fromArgs:e=>Us(`--orm`,e.options?.orm,qs),when:e=>Q(e.templateId),defaultValue:()=>`drizzle`,label:`ORM`,prompt:(e,t)=>F({message:`Qual ORM deseja usar no banco?`,initialValue:t??`drizzle`,options:[{value:`prisma`,label:`Prisma`},{value:`drizzle`,label:`Drizzle (padrão)`}]}),summary:e=>e?`${L.default.green(`ORM:`)} ${e}`:void 0}),$({id:`installDependencies`,fromArgs:e=>e.options?.install!==!1&&void 0,defaultValue:()=>!0,label:`Instalar dependências`,prompt:(e,t)=>Vt({message:`Deseja instalar os pacotes agora?`,initialValue:t??!0}),summary:e=>`${L.default.green(`Dependencias:`)} ${e?`instaladas`:`pendentes`}`}),...Vs(),$({id:`workers`,fromArgs:(e,t)=>{if(e.options?.workers!==void 0){if(t.templateId!==`monolith`||t.apiHosting===`cloudflare`)throw Error(`--workers exige o template monolith com a API em servidor.`);return $s(e.options.workers)}if(e.options?.queues!==void 0){if(t.apiHosting!==`cloudflare`)throw Error(`--queues exige API no Cloudflare.`);return Ys(e.options.queues)}},when:e=>e.templateId===`monolith`||e.apiHosting===`cloudflare`,fallback:[],defaultValue:()=>[],label:`Workers e filas`,prompt:async(e,t)=>{if(e.apiHosting!==`cloudflare`){let e=await N({message:`Quais workers BullMQ voce quer criar?`,required:!1,initialValues:(t??[]).map(e=>ec(e)).filter(e=>e!==void 0),options:[{value:`emails`,label:`emails`,hint:`Envia os e-mails da API pela plataforma Messaging (liga o messaging).`},{value:`webhooks`,label:`webhooks`,hint:`Entrega webhooks assinados (Standard Webhooks) a partir de um outbox.`},{value:`generic`,label:`generic`,hint:"Worker `jobs` com fila e retentativa, para preencher."}]});return typeof e==`symbol`?e:Qs(e)}let n=await F({message:`Deseja incluir filas Cloudflare Queues?`,initialValue:(t?.length??0)>0,options:[{value:!1,label:`Nao`},{value:!0,label:`Sim`}]});if(typeof n==`symbol`)return n;if(!n)return[];let r=await $t({message:`Quais filas Cloudflare deseja criar? (nomes separados por virgula)`,placeholder:`emails, webhooks`,...t===void 0?{}:{initialValue:t.map(e=>e.name).join(`, `)},defaultValue:``});return typeof r==`string`?Ys(r):r},summary:(e,t)=>{if(e.length===0)return;let n=`${L.default.green(`Workers:`)} ${e.map(e=>e.name).join(`, `)}`;return e.some(e=>e.kind===`webhooks`)&&!t.implementAuthModule?`${n}\n${L.default.yellow(`Webhooks:`)} sem o modulo de auth NestJS, so o WebhooksService e gerado (as rotas de endpoints exigem sessao).`:n}}),$({id:`messaging`,when:e=>Q(e.templateId),fromArgs:(e,t)=>e.options?.messaging??(t.workers?.some(e=>e.kind===`messaging`)?!0:void 0),fallback:!1,defaultValue:()=>!1,label:`Messaging`,prompt:(e,t)=>F({message:`Deseja incluir o módulo de messaging para envio de e-mails, webpush, SMS e mensagens de WhatsApp?`,initialValue:t??!1,options:[{value:!1,label:`Não incluir`,hint:`Sem o módulo de messaging.`},{value:!0,label:`Incluir módulo de messaging`,hint:`Habilita os canais de e-mail, webpush, SMS e WhatsApp.`}]}),summary:(e,t)=>{if(!Q(t.templateId))return;let n=t.workers.some(e=>e.kind===`messaging`);return`${L.default.green(`Messaging:`)} ${e?n?`incluido, pelo worker emails`:`incluido, direto da API`:`desativado`}`}}),$({id:`workflows`,defaultValue:()=>Gs.map(e=>e.value),label:`Workflows do GitHub`,prompt:(e,t)=>N({message:`Quais workflows do GitHub voce quer incluir?`,initialValues:t??Gs.map(e=>e.value),options:Gs}),summary:e=>`${L.default.green(`Workflows:`)} ${e.length>0?e.map(e=>Gs.find(t=>t.value===e)?.label??e).join(`, `):`nenhum`}`}),$({id:`authProviders`,when:e=>(e.setupFeatures??[]).includes(`betterAuth`),fallback:[],defaultValue:()=>[],label:`Auth providers`,prompt:(e,t)=>N({message:`Quais providers do Better Auth você quer habilitar? (opcional; deixe vazio para usar apenas SSO ou plugins)`,required:!1,initialValues:t??[],options:Ws}),summary:e=>e.length>0?`${L.default.green(`Auth providers:`)} ${e.join(`, `)}`:void 0}),$({id:`telemetryAdapter`,when:e=>(e.setupFeatures??[]).includes(`telemetry`),fallback:`posthog`,defaultValue:()=>`posthog`,label:`Telemetria`,prompt:(e,t)=>F({message:`Qual destino de telemetria voce quer usar?`,initialValue:t??`posthog`,options:[{value:`posthog`,label:`PostHog`,hint:`default · eventos de produto e excecoes`},{value:`betterstack`,label:`Better Stack`,hint:`logs, metricas, traces e erros via OTLP`}]}),summary:(e,t)=>t.setupFeatures.includes(`telemetry`)?`${L.default.green(`Telemetry:`)} ${e}`:void 0}),$({id:`authPlugins`,when:e=>(e.setupFeatures??[]).includes(`betterAuth`),fallback:[],defaultValue:()=>[],label:`Auth plugins`,prompt:(e,t)=>N({message:`Quais plugins do Better Auth voce quer habilitar?`,required:!1,initialValues:t??[],options:Vi.filter(t=>t.value!==`magicLink`||e.messaging)}),summary:e=>e.length>0?`${L.default.green(`Auth plugins:`)} ${e.join(`, `)}`:void 0}),$({id:`rockfellerSso`,when:e=>Q(e.templateId)&&(e.authPlugins??[]).includes(`rockfellerSso`),defaultValue:()=>({clientId:``,clientSecret:``}),label:`Credenciais do Rockfeller SSO`,prompt:async(e,t)=>{let n=await $t({message:`Qual é o client ID do Rockfeller SSO? (opcional; vazio para preencher depois no .env)`,...t===void 0?{}:{initialValue:t.clientId},defaultValue:``});if(typeof n!=`string`)return n;let r=await Jt({message:`Qual é o client secret do Rockfeller SSO? (opcional; vazio para preencher depois no .env)`});return typeof r==`symbol`?r:{clientId:n.trim(),clientSecret:(r??``).trim()}},review:e=>Hs(e),summary:e=>e?`${L.default.green(`Rockfeller SSO:`)} ${Hs(e)}`:void 0}),$({id:`implementAuthModule`,when:e=>(e.setupFeatures??[]).includes(`betterAuth`)&&Q(e.templateId),fallback:!1,defaultValue:()=>!0,label:`Implementação de auth`,prompt:(e,t)=>F({message:`Como voce quer sair do scaffold de auth?`,initialValue:t??!0,options:[{value:!1,label:`So configurar Better Auth`,hint:`Gera a instancia e as rotas base, sem modulo Nest pronto.`},{value:!0,label:`Implementar modulo NestJS`,hint:`Usa nestjs-better-auth com modulo e guard prontos.`}]}),summary:(e,t)=>t.setupFeatures.includes(`betterAuth`)&&Q(t.templateId)?`${L.default.green(`Auth implementacao:`)} ${e?`modulo NestJS com nestjs-better-auth`:`instancia Better Auth base`}`:void 0}),$({id:`skills`,defaultValue:()=>[],label:`Skills recomendadas`,prompt:async(t,n)=>{let r=e(t.templateId),i=Xt();i.start(`Buscando skills recomendadas ainda não instaladas...`);let a=await zs(r,process.cwd());return i.stop(a.length>0?`${a.length} skill(s) recomendada(s) disponível(is)`:`Todas as skills recomendadas já estão instaladas`),a.length===0?[]:N({message:`Quais skills recomendadas deseja incluir? (opcional)`,required:!1,initialValues:n??[],options:a.map(e=>({value:e.id,label:e.label,hint:e.description}))})},summary:e=>`${L.default.green(`Skills:`)} ${e.length>0?e.join(`, `):`nenhuma`}`})];function nc(t){t.command(`new [template] [name]`).aliases([`generate`,`gen`,`create`]).description(`Cria uma nova base de projeto a partir de um template`).option(`-n, --name <name>`,`Nome do projeto`).option(`-y, --yes`,`Sem perguntas: usa os padroes (exige template e nome)`).option(`--package-manager <manager>`,`pnpm ou bun`).option(`--runtime <runtime>`,`node ou bun: onde a API e os workers rodam (api e monolith)`).option(`--no-install`,`Nao instala as dependencias`).option(`--orm <orm>`,`prisma ou drizzle (api e monolith)`).option(`--serverless`,`Hospeda todos os apps no Cloudflare Workers/Pages`).option(`--api-hosting <hosting>`,`traditional, railway ou cloudflare`).option(`--web-hosting <hosting>`,`traditional, vercel ou cloudflare`).option(`--web-type <type>`,`application ou landing (estatica)`).option(`--web-adapter <adapter>`,`vinext ou opennext (website no Cloudflare)`).option(`--messaging`,`Inclui modulo opcional de envio de e-mail`).option(`--kv`,`Habilita cache Cloudflare KV na API serverless`).option(`--queues <names>`,`Filas Cloudflare, nomes separados por virgula`).option(`--workers <presets>`,`Workers BullMQ do monolith: emails, webhooks, generic`).action(async(t,n,r)=>{let i={template:t,name:n,options:r},a=us({yes:r?.yes,isTTY:!!process.stdout.isTTY,env:process.env});a&&console.log(`\n${ms(process.stdout.columns??80)}\n`);let o=await Fs(tc,i),s=Pa({templateId:o.templateId,features:o.setupFeatures}),c=Xt();c.start(`Gerando arquivos...`);let l;try{l=await cs({name:o.projectName.trim(),hosting:{api:o.apiHosting,web:o.webHosting,webType:o.webType,webAdapter:o.webAdapter,kv:o.kv},templateId:o.templateId,packageManager:o.packageManager,runtime:o.runtime,installDependencies:o.installDependencies,fullSetup:Fa(s,o.templateId),setupFeatures:o.setupFeatures,authProviders:o.authProviders,authPlugins:o.authPlugins,telemetryAdapter:o.telemetryAdapter,workers:o.workers,messaging:o.messaging,implementAuthModule:o.implementAuthModule,databaseOrm:o.databaseOrm,workflows:o.workflows,envValues:{ROCKFELLER_CLIENT_ID:o.rockfellerSso?.clientId??``,ROCKFELLER_CLIENT_SECRET:o.rockfellerSso?.clientSecret??``},cwd:process.cwd()});let t=await Ii(e(o.templateId).filter(e=>o.skills.includes(e.id)));c.stop(`Projeto criado em ${L.default.cyan(l.targetDir)}`),Ls({steps:tc,answers:o,result:l,installedSkills:t.filter(e=>!e.error).map(e=>e.skill.label),skillCommands:Fi(t.filter(e=>e.error).map(e=>e.skill))})}catch(e){throw c.stop(L.default.red(`Falha ao criar projeto.`)),e}a&&await Ds(l.targetDir,l.projectDirectoryName)})}const rc=[[`node`,`Node.js`],[`npm`,`npm`],[`npx`,`npx`],[`bun`,`Bun`],[`pnpm`,`pnpm`],[`cargo`,`Cargo`],[`git`,`Git`],[`claude`,`Claude Code`],[`codex`,`Codex CLI`],[`curl`,`curl`],[`code-review-graph`,`code-review-graph`]];async function ic(e,t={}){let n=await Promise.all(rc.map(async([n,r])=>oc(n,r,e,t))),r=t.homedir?.()??se(),i=[c.join(r,`.claude`,`settings.json`),c.join(r,`.claude`,`CLAUDE.md`),c.join(r,`.codex`,`AGENTS.md`),c.join(r,`.codex`,`config.toml`)],a=(await Promise.all(i.map(async e=>await cc(e)?e:void 0))).filter(e=>!!e);return{platform:process.platform,architecture:process.arch,shell:process.env.SHELL??process.env.ComSpec??`desconhecido`,tools:n,configFiles:a}}async function ac(e,t=process.cwd()){try{return(await n(e,[`--version`],{cwd:t})).exitCode===0}catch{return!1}}async function oc(e,t,r,i){try{let a=await(i.run??((e,t,i)=>n(e,t,{cwd:i?.cwd??r})))(e,[`--version`],{cwd:r}),o=`${a.stdout}\n${a.stderr}`.trim();if(a.exitCode===0)return{name:t,command:e,available:!0,version:sc(o)}}catch{}return{name:t,command:e,available:!1}}function sc(e){return e.split(/\r?\n/,1)[0]?.trim()||void 0}async function cc(e){try{return await b(e),!0}catch{return!1}}async function lc(e={}){let t=e.home??se(),n=new Date(e.now??Date.now()).toISOString().replaceAll(`:`,`-`),r=[c.join(t,`.claude`,`settings.json`),c.join(t,`.claude`,`CLAUDE.md`),c.join(t,`.codex`,`AGENTS.md`),c.join(t,`.codex`,`config.toml`)],i=[];for(let e of r)try{await b(e);let t=`${e}.rock-backup-${n}`;await S(c.dirname(t),{recursive:!0}),await x(e,t),i.push(t)}catch{}return i}async function uc(e){let t=e.dependencies?.run??((t,r,i)=>n(t,r,{cwd:i?.cwd??e.cwd})),r=`code-review-graph`,i=[`build`];if(e.dryRun)return{status:`ok`,message:`Atualização do code-review graph planejada.`,commands:[`${r} ${i.join(` `)}`]};try{let n=await t(r,i,{cwd:e.cwd});return n.exitCode===0?{status:`ok`,message:`Code-review graph atualizado.`,commands:[`${r} ${i.join(` `)}`]}:{status:`error`,message:`A atualização do code-review graph falhou.`,details:[n.stderr.trim()||n.stdout.trim()].filter(Boolean),commands:[`${r} ${i.join(` `)}`]}}catch{return{status:`warn`,message:`code-review-graph não está instalado.`,details:["Instale-o separadamente e execute `code-review-graph build` quando necessário."],commands:[]}}}const dc=`https://raw.githubusercontent.com/rtk-ai/rtk/master/install.sh`;async function fc(e){let t=e.dependencies?.run??((t,r,i)=>n(t,r,{cwd:i?.cwd??e.cwd})),r=[],i=await mc(t,e.cwd);if(i)return{status:`ok`,message:`RTK ja esta instalado (${i}).`,commands:r};let a=await hc(t,`rtk`,e.cwd);if((e.installMethod??(await hc(t,`cargo`,e.cwd)?`cargo`:`official-script`))===`cargo`){let n=[`install`,`--git`,`https://github.com/rtk-ai/rtk`];if(r.push(gc(`cargo`,n)),!e.dryRun){let i=await t(`cargo`,n,{cwd:e.cwd});if(i.exitCode!==0)return{status:`error`,message:`A instalação do RTK via Cargo falhou.`,details:[...a?["Já existe um executável `rtk`, mas ele não passou em `rtk gain`."]:[],i.stderr.trim()||i.stdout.trim()].filter(Boolean),commands:r}}}else if(r.push(`curl -fsSL ${dc} -o <arquivo-temporario>`,`sh <arquivo-temporario>`),!e.dryRun){if(process.platform===`win32`)return{status:`warn`,message:`O instalador oficial exige shell Unix; use WSL ou Cargo no Windows.`,commands:r};let n=await ee(c.join(ce(),`rock-rtk-`)),i=c.join(n,`install.sh`);try{let n=await t(`curl`,[`-fsSL`,dc,`-o`,i],{cwd:e.cwd});if(n.exitCode!==0)throw Error(n.stderr.trim()||`download falhou`);let r=await t(`sh`,[i],{cwd:e.cwd,shell:!1});if(r.exitCode!==0)throw Error(r.stderr.trim()||r.stdout.trim()||`instalação falhou`)}catch(e){return{status:`error`,message:`O instalador oficial do RTK falhou.`,details:[...a?["Já existe um executável `rtk`, mas ele não passou em `rtk gain`."]:[],String(e)],commands:r}}finally{await ne(n,{recursive:!0,force:!0})}}if(e.dryRun)return{status:`ok`,message:`Instalação do RTK planejada.`,commands:r};let o=await mc(t,e.cwd);return o?{status:`ok`,message:`RTK instalado e validado (${o}).`,commands:r}:{status:`error`,message:"RTK foi instalado, mas `rtk gain` não pôde ser validado.",commands:r}}async function pc(e,t){let r=t.dependencies?.run??((e,r,i)=>n(e,r,{cwd:i?.cwd??t.cwd})),i=[],a=[];for(let n of e){let e=n===`codex`?[`init`,`--global`,`--codex`]:[`init`,`--global`];if(i.push(gc(`rtk`,e)),t.dryRun)continue;let o=await r(`rtk`,e,{cwd:t.cwd});if(o.exitCode!==0)return{status:`error`,message:`Não foi possível configurar o RTK no ${n}.`,details:[o.stderr.trim()||o.stdout.trim()].filter(Boolean),commands:i};a.push(`${n} configurado`)}return{status:`ok`,message:t.dryRun?`Configuração dos agentes planejada.`:`RTK configurado nos agentes selecionados.`,details:a,commands:i}}async function mc(e,t){try{if((await e(`rtk`,[`gain`],{cwd:t})).exitCode!==0)return;let n=await e(`rtk`,[`--version`],{cwd:t});return n.exitCode===0?`${n.stdout||n.stderr}`.trim().split(/\r?\n/,1)[0]:`versão desconhecida`}catch{return}}async function hc(e,t,n){try{return(await e(t,[`--version`],{cwd:n})).exitCode===0}catch{return!1}}function gc(e,t){return[e,...t].join(` `)}const _c={diagnostics:`Diagnóstico`,skills:`Skills globais`,rtk:`Instalação do RTK`,agents:`Configuração Claude/Codex`,graph:`Code-review graph`};function vc(e){return{id:e,label:_c[e],status:`skipped`,message:`Etapa ignorada.`}}async function yc(e,n={}){let r=e.agents?.length?e.agents:[`claude-code`,`codex`],i=await ic(e.cwd,n),a=[{id:`diagnostics`,label:_c.diagnostics,status:`ok`,message:`Diagnóstico concluído.`,details:[`Plataforma: ${i.platform}/${i.architecture}`,`Shell: ${i.shell}`,...i.tools.map(e=>`${e.name}: ${e.available?e.version??`disponível`:`não encontrado`}`),...i.configFiles.length>0?[`Configurações encontradas: ${i.configFiles.join(`, `)}`]:[`Nenhuma configuração global de agente encontrada.`]]}],o=[],s=t=>(!e.only||e.only.includes(t))&&!e.skip?.includes(t);if(s(`skills`)){let{official:i,optional:s}=(await import(`./skills-DuE-XnBp.js`)).getSetupSkills(),c=e.optionalSkillIds??(e.includeOptionalSkills?s.map(e=>e.id):[]),l=e.skillIds??c,u=[...i,...s].filter(e=>l.includes(e.id)),d=await t(u,r,{cwd:e.cwd,dryRun:e.dryRun,dependencies:n});o.push(d.command??``),a.push({id:`skills`,label:_c.skills,status:d.status,message:d.message,details:d.details})}else a.push(vc(`skills`));if(s(`rtk`)){let t=await fc({cwd:e.cwd,dryRun:e.dryRun,installMethod:e.installMethod,dependencies:n});o.push(...t.commands),a.push({id:`rtk`,label:_c.rtk,status:t.status,message:t.message,details:t.details})}else a.push(vc(`rtk`));if(s(`agents`)){let t=a.find(e=>e.id===`rtk`);if(t?.status===`ok`||t?.status===`skipped`){let t=e.dryRun?[]:await lc({home:n.homedir?.(),now:n.now?.()}),i=await pc(r,{cwd:e.cwd,dryRun:e.dryRun,dependencies:n});o.push(...i.commands),a.push({id:`agents`,label:_c.agents,status:i.status,message:i.message,details:[...t.length>0?[`Backup criado: ${t.join(`, `)}`]:[],...i.details??[]]})}else a.push({id:`agents`,label:_c.agents,status:`warn`,message:`Configuração ignorada porque o RTK não foi validado.`})}else a.push(vc(`agents`));if(s(`graph`)){let t=await uc({cwd:e.cwd,dryRun:e.dryRun,dependencies:n});o.push(...t.commands),a.push({id:`graph`,label:_c.graph,status:t.status,message:t.message,details:t.details})}else a.push(vc(`graph`));return{diagnostics:i,steps:a,commands:o.filter(Boolean)}}async function bc(e,t){return e.yes?t?`cargo`:`official-script`:R(await F({message:`Como deseja instalar o RTK se ele ainda não estiver instalado?`,options:[...t?[{value:`cargo`,label:`Cargo`,hint:`Usa Rust/Cargo e o repositório oficial.`}]:[],{value:`official-script`,label:`Instalador oficial`,hint:`Baixa o instalador do repositório rtk-ai/rtk.`}]}),`Operação cancelada.`)}const xc=[{value:`diagnostics`,label:`Diagnóstico`,hint:`Ferramentas, versões, permissões e configurações.`},{value:`skills`,label:`Skills globais`,hint:`Skills oficiais Rockfeller para Claude Code e Codex.`},{value:`rtk`,label:`RTK`,hint:`Instala e valida o Rust Token Killer.`},{value:`agents`,label:`Claude/Codex`,hint:`Configura o RTK nos agentes selecionados.`},{value:`graph`,label:`Code-review graph`,hint:`Atualiza o grafo local do repositório.`}];function Sc(e,t){return(!e.only||e.only.includes(t))&&!e.skip?.includes(t)}function Cc(e){return{cwd:process.cwd(),dryRun:e.dryRun,yes:e.yes,optionalSkills:e.optionalSkills,skillIds:e.skills===!1?[]:e.skills?wc(e.skills):void 0,agents:e.agents?Tc(e.agents):void 0,only:e.only?Ec(e.only):void 0,skip:e.skip?Ec(e.skip):void 0}}function wc(e){let{official:t,optional:n}=r(),i=new Set([...t,...n].map(e=>e.id));return[...new Set(e.split(`,`).map(e=>{let t=e.trim();if(!i.has(t))throw Error(`Skill desconhecida: ${t}`);return t}))]}function Tc(e){let t=e.split(`,`).map(e=>{if(e.trim()===`claude`)return`claude-code`;if(e.trim()===`codex`)return`codex`;throw Error(`Agente desconhecido: ${e}`)});if(t.length===0)throw Error(`Informe pelo menos um agente.`);return[...new Set(t)]}function Ec(e){return e.split(`,`).map(e=>{let t=e.trim();if(!xc.some(e=>e.value===t))throw Error(`Etapa desconhecida: ${e}`);return t})}function Dc(e,t){t?console.log(JSON.stringify(e,null,2)):Oc(e)}function Oc(e){console.log(``),console.log(L.default.bold(`Resumo do setup`));for(let t of e.steps){let e=t.status===`ok`?L.default.green(`OK`):t.status===`warn`?L.default.yellow(`WARN`):t.status===`error`?L.default.red(`ERROR`):L.default.dim(`SKIP`);console.log(`${e} ${t.label}: ${t.message}`);for(let e of t.details??[])console.log(` ${L.default.dim(`-`)} ${e}`)}if(e.commands.length>0){console.log(``),console.log(L.default.bold(`Comandos executados ou planejados`));for(let t of e.commands)console.log(` ${L.default.dim(`$`)} ${t}`)}let t=e.steps.filter(e=>e.status===`error`).length;console.log(``),Gt(t===0?L.default.green(`Setup concluído. Reinicie Claude Code e Codex para aplicar as alterações.`):L.default.yellow(`Setup concluído com falhas; revise os comandos e avisos acima.`)),t>0&&(process.exitCode=1)}function kc(e){e.command(`setup`).description(`Prepara globalmente o ambiente para Claude Code e Codex`).option(`--yes`,`Executa sem prompts interativos`).option(`--dry-run`,`Mostra o que seria feito sem modificar o computador`).option(`--agents <agents>`,`Agentes separados por vírgula: claude,codex`).option(`--only <steps>`,`Executa apenas etapas separadas por vírgula`).option(`--skip <steps>`,`Ignora etapas separadas por vírgula`).option(`--skills <ids>`,`Instala somente as skills selecionadas, separadas por virgula`).option(`--no-skills`,`Continua sem instalar nenhuma skill`).option(`--no-optional-skills`,`Não oferece skills de terceiros`).option(`--json`,`Emite o relatório em JSON`).action(async e=>{let t=Cc(e);if(e.json||e.yes||e.dryRun){Dc(await yc({...t,skillIds:t.skillIds??[]}),!!e.json);return}let{official:n,optional:i}=r();P([L.default.bold(`O setup global vai preparar seu ambiente.`),``,`• Todas as skills são opcionais; nenhuma vem selecionada.`,`• O RTK será instalado e configurado nos agentes selecionados.`,`• Configurações existentes serão preservadas e terão backup antes da alteração.`,`• O code-review graph é opcional e pode demorar alguns minutos.`].join(`
|
|
1535
|
+
`),`rock setup`);let a=t.agents??R(await N({message:`Quais agentes deseja configurar?`,initialValues:[`claude-code`,`codex`],options:[{value:`claude-code`,label:`Claude Code`,hint:`Skills globais e RTK.`},{value:`codex`,label:`Codex`,hint:`Skills globais e RTK.`}]}),`Operação cancelada.`);if(a.length===0)throw Error(`Selecione pelo menos um agente.`);let o=[...n,...e.optionalSkills===!1?[]:i],s=t.skillIds??(Sc(t,`skills`)?R(await N({message:`Quais skills deseja instalar? (opcional)`,required:!1,initialValues:[],options:o.map(e=>({value:e.id,label:e.label,hint:e.description}))}),`Operação cancelada.`):[]),c=Sc(t,`rtk`)?await bc(t,await ac(`cargo`,t.cwd)):void 0,l=Sc(t,`graph`),u=l?R(await Vt({message:`Deseja atualizar o code-review graph deste repositório?`,initialValue:!1}),`Operação cancelada.`):!1;Oc(await yc({...t,agents:a,skillIds:s,installMethod:c,skip:u||!l?t.skip:[...t.skip??[],`graph`]}))})}async function Ac(e){let t=c.join(e,`.github`,`workflows`);try{let e=(await te(t,{withFileTypes:!0})).filter(e=>e.isFile()).map(e=>e.name).sort();return e.length===0?{id:`ci`,label:`CI`,level:`warn`,message:`Diretorio .github/workflows existe, mas sem workflows.`}:{id:`ci`,label:`CI`,level:`ok`,message:`Workflows encontrados.`,details:e.map(e=>`.github/workflows/${e}`)}}catch(e){if(e.code===`ENOENT`)return{id:`ci`,label:`CI`,level:`warn`,message:`Nenhum workflow de CI encontrado.`};throw e}}function jc(e){return typeof e==`string`?`bin: ${e}`:`bin: ${Object.entries(e??{}).map(([e,t])=>`${e} -> ${t}`).join(`, `)}`}async function Mc(e){try{let t=await C(c.join(e,`package.json`),`utf8`);return JSON.parse(t)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function Nc(e){return e?.split(`@`)[0]}async function Pc(e){let t=await Mc(e);return t?t.name?t.bin?{id:`package`,label:`Package metadata`,level:`ok`,message:`Pacote ${t.name} com bin configurado.`,details:[jc(t.bin)]}:{id:`package`,label:`Package metadata`,level:`ok`,message:`Pacote ${t.name} configurado.`}:{id:`package`,label:`Package metadata`,level:`warn`,message:`package.json sem campo name.`}:{id:`package`,label:`Package metadata`,level:`error`,message:`package.json nao encontrado.`}}const Fc={bun:[`bun.lock`,`bun.lockb`],pnpm:[`pnpm-lock.yaml`],npm:[`package-lock.json`],yarn:[`yarn.lock`]},Ic=Object.values(Fc).flat(),Lc=[`vercel.json`,`render.yaml`,`railway.json`,`fly.toml`,`netlify.toml`,`wrangler.toml`,`Procfile`];async function Rc(e,t){return(await Promise.all(t.map(async t=>await Bc(c.join(e,t))?t:null))).filter(e=>e!==null)}async function zc(e,t){for(let n of t)if(await Bc(c.join(e,n)))return n}async function Bc(e){try{return await b(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function Vc(e){let t=await Rc(e,Lc),n=await zc(e,[`.github/workflows/release.yml`,`.github/workflows/release.yaml`,`.github/workflows/release-publish.yml`,`.github/workflows/release-publish.yaml`,`.github/workflows/deploy.yml`,`.github/workflows/deploy.yaml`,`.github/workflows/publish.yml`,`.github/workflows/publish.yaml`]),r=await Mc(e),i=r?.private===!1&&r.publishConfig?.access===`public`;return t.length===0&&!n&&!i?{id:`deploy`,label:`Deploy/Publish`,level:`warn`,message:`Nenhuma configuracao clara de deploy ou publish foi encontrada.`}:{id:`deploy`,label:`Deploy/Publish`,level:`ok`,message:`Existe pelo menos um caminho de deploy ou publish configurado.`,details:[...t,...n?[n]:[],...i?[`package.json publishConfig publico`]:[]]}}async function Hc(e){let t=await zc(e,[`Dockerfile`,`dockerfile`]);if(!t)return{id:`dockerfile`,label:`Dockerfile`,level:`warn`,message:`Dockerfile nao encontrado.`};let n=(await C(c.join(e,t),`utf8`)).toLowerCase(),r=n.includes(`from `),i=n.includes(`workdir `),a=n.includes(`cmd `)||n.includes(`entrypoint `);return r&&i&&a?{id:`dockerfile`,label:`Dockerfile`,level:`ok`,message:`${t} parece completo para build/run.`}:{id:`dockerfile`,label:`Dockerfile`,level:`warn`,message:`${t} existe, mas parece incompleto.`,details:[`FROM: ${r?`ok`:`faltando`}`,`WORKDIR: ${i?`ok`:`faltando`}`,`CMD/ENTRYPOINT: ${a?`ok`:`faltando`}`]}}async function Uc(e){let t=await zc(e,[`.env`]),n=await zc(e,[`.env.example`]);if(!t&&!n)return{id:`env`,label:`.env.example`,level:`warn`,message:`Nem .env nem .env.example foram encontrados.`};if(t&&!n)return{id:`env`,label:`.env.example`,level:`warn`,message:`.env existe, mas .env.example nao foi encontrado.`};if(!t&&n)return{id:`env`,label:`.env.example`,level:`ok`,message:`.env.example existe; .env local nao esta presente para comparar.`};if(!t||!n)return{id:`env`,label:`.env.example`,level:`warn`,message:`Nao foi possivel comparar .env com .env.example.`};let[r,i]=await Promise.all([C(c.join(e,t),`utf8`),C(c.join(e,n),`utf8`)]),a=An(r),o=An(i),s=a.filter(e=>!o.includes(e)),l=o.filter(e=>!a.includes(e));if(s.length===0&&l.length===0)return{id:`env`,label:`.env.example`,level:`ok`,message:`.env.example esta alinhado com .env.`,details:[`Variaveis comparadas: ${a.length}`]};let u=[];return s.length>0&&u.push(`Faltando no .env.example: ${s.join(`, `)}`),l.length>0&&u.push(`Sobrando no .env.example: ${l.join(`, `)}`),{id:`env`,label:`.env.example`,level:`warn`,message:`.env.example precisa ser sincronizado com .env.`,details:u}}async function Wc(e){return await zc(e,[`.git`])?{id:`git`,label:`Git`,level:`ok`,message:`Repositorio Git inicializado.`}:{id:`git`,label:`Git`,level:`warn`,message:`Diretorio .git nao encontrado.`}}async function Gc(e){return await zc(e,[`.gitignore`])?{id:`gitignore`,label:`.gitignore`,level:`ok`,message:`.gitignore encontrado.`}:{id:`gitignore`,label:`.gitignore`,level:`warn`,message:`.gitignore nao encontrado.`}}async function Kc(e){let t=await Mc(e);if(!t)return{id:`package-manager`,label:`Package manager`,level:`error`,message:`package.json nao encontrado.`};let n=Nc(t.packageManager),r=await Rc(e,Ic);if(!n)return{id:`package-manager`,label:`Package manager`,level:`warn`,message:`package.json sem campo packageManager.`,details:r.length?[`Lockfiles encontrados: ${r.join(`, `)}`]:[`Nenhum lockfile encontrado.`]};let i=Fc[n]??[],a=i.some(e=>r.includes(e)),o=r.some(e=>!i.includes(e));return a?o?{id:`package-manager`,label:`Package manager`,level:`warn`,message:`packageManager e lockfile principal batem (${n}), mas existem lockfiles extras.`,details:[`Lockfiles encontrados: ${r.join(`, `)}`]}:{id:`package-manager`,label:`Package manager`,level:`ok`,message:`packageManager e lockfile estao alinhados em ${n}.`,details:[`Lockfile: ${r.join(`, `)}`]}:{id:`package-manager`,label:`Package manager`,level:`error`,message:`packageManager declara ${n}, mas o lockfile correspondente nao existe.`,details:r.length?[`Lockfiles encontrados: ${r.join(`, `)}`]:[`Esperado: ${i.join(` ou `)}`]}}async function qc(e){let t=await zc(e,[`README.md`,`README.mdx`,`README`]);return t?{id:`readme`,label:`README`,level:`ok`,message:`Arquivo encontrado: ${t}.`}:{id:`readme`,label:`README`,level:`error`,message:`README nao encontrado.`}}async function Jc(e){let t=await Mc(e);if(!t)return{id:`scripts`,label:`Scripts`,level:`error`,message:`package.json nao encontrado.`};let n=[`lint`,`typecheck`,`test`,`build`],r=t.scripts??{},i=n.filter(e=>!r[e]);return i.length===0?{id:`scripts`,label:`Scripts`,level:`ok`,message:`Scripts principais de qualidade estao presentes.`,details:n.map(e=>`${e}: ${r[e]}`)}:{id:`scripts`,label:`Scripts`,level:`warn`,message:`Faltam scripts recomendados de qualidade.`,details:[`Faltando: ${i.join(`, `)}`]}}async function Yc(e=process.cwd()){let t=await Promise.all([Kc(e),qc(e),Ac(e),Uc(e),Hc(e),Vc(e),Jc(e),Gc(e),Wc(e),Pc(e)]);return{rootDir:e,checks:t,counts:t.reduce((e,t)=>(e[t.level]+=1,e),{ok:0,warn:0,error:0})}}function Xc(e){e.command(`status`).description(`Mostra um status geral da configuracao do projeto atual`).action(async()=>{let e=await Yc(process.cwd());console.log(L.default.bold(`Status do projeto: ${e.rootDir}`)),console.log(``);for(let t of e.checks){console.log(Zc(t));for(let e of t.details??[])console.log(` ${L.default.dim(`-`)} ${e}`)}console.log(``),console.log([`${L.default.green(`${e.counts.ok} ok`)}`,`${L.default.yellow(`${e.counts.warn} avisos`)}`,`${L.default.red(`${e.counts.error} erros`)}`].join(` `)),e.counts.error>0&&(process.exitCode=1)})}function Zc(e){return`${e.level===`ok`?L.default.green(`OK`):e.level===`warn`?L.default.yellow(`WARN`):L.default.red(`ERROR`)} ${L.default.bold(e.label)}: ${e.message}`}function Qc(){let e=process.env.XDG_CONFIG_HOME??process.env.APPDATA??c.join(se(),`.config`);return c.join(e,`rock`,`updates.json`)}async function $c(e){try{let t=await(e?.readFile??C)(e?.filePath??Qc(),`utf8`),n=JSON.parse(t);return typeof n.skippedVersion==`string`?n.skippedVersion:void 0}catch{return}}async function el(e,t){try{let n=t?.filePath??Qc();await(t?.mkdir??S)(c.dirname(n),{recursive:!0}),await(t?.writeFile??ie)(n,`${JSON.stringify({skippedVersion:e})}\n`,`utf8`)}catch{}}function tl(e){let t=/^v?(\d+)\.(\d+)\.(\d+)$/.exec(e.trim());if(t)return t.slice(1).map(Number)}function nl(e,t){let n=tl(e),r=tl(t);if(!n||!r)return!1;for(let[e,t]of n.entries())if(t!==r[e])return t>(r[e]??0);return!1}async function rl(e,t,n,r){try{let i=await t(e,{headers:n,signal:AbortSignal.timeout(r)});return i.ok?i.json():void 0}catch{return}}async function il(e){let t=e?.fetch??globalThis.fetch,n=e?.timeoutMs??750,r=await rl(`https://api.github.com/repos/rockfellerfranchising/npm/releases/latest`,t,{Accept:`application/vnd.github+json`},n),i=typeof r?.tag_name==`string`?r.tag_name.replace(/^v/,``):void 0;if(i&&tl(i))return{version:i};let a=await rl(`https://registry.npmjs.org/franchising/latest`,t,{Accept:`application/json`},n),o=typeof a?.version==`string`?a.version:void 0;return o&&tl(o)?{version:o}:void 0}function al(e=ae(import.meta.url)){let t=e.replaceAll(`\\`,`/`);return t.includes(`/.bun/install/global/node_modules/`)?`bun`:t.includes(`/pnpm/global/`)||t.includes(`/node_modules/.pnpm/`)?`pnpm`:t.includes(`/yarn/global/node_modules/`)?`yarn`:`npm`}async function ol(e,t){let n=t?.run??((e,t)=>I(e,t,{cwd:process.cwd()})),r=t?.packageManager??al(),i=`franchising@${e}`;r===`bun`?await n(`bun`,[`install`,`--global`,i]):r===`pnpm`?await n(`pnpm`,[`add`,`--global`,i]):r===`yarn`?await n(`yarn`,[`global`,`add`,i]):await n(`npm`,[`install`,`--global`,i])}function sl(e=process.env,t=!!(process.stdin.isTTY&&process.stdout.isTTY)){return e.CI||e.ROCK_NO_UPDATE_CHECK?!1:t}async function cl(e,t={getLatestRelease:il,getSkippedUpdateVersion:$c,select:F,skipUpdateUntilNextRelease:el,updateCli:ol}){let n=await t.getLatestRelease();if(!n||!nl(n.version,e))return`up-to-date`;if(await t.getSkippedUpdateVersion()===n.version)return`skipped-version`;let r=await t.select({message:`Nova versao ${n.version} disponivel. Deseja atualizar agora?`,options:[{value:`install`,label:`Instalar nova versao`},{value:`skip`,label:`Pular`},{value:`skip-until-next-update`,label:`Pular ate a proxima atualizacao`}]});return r===`skip-until-next-update`?(await t.skipUpdateUntilNextRelease(n.version),`skipped-version`):r!==`install`||ot(r)?`skipped`:(await t.updateCli(n.version),Gt(`Rock atualizado para a versao ${n.version}.`),`updated`)}function ll(e,t){e.command(`update`).alias(`upgrade`).description(`Atualiza a CLI para a ultima release disponivel`).action(async()=>{let e=await il();if(!e)throw Error(`Nao foi possivel consultar as releases do GitHub.`);nl(e.version,t)?(await ol(e.version),Gt(`Rock atualizado para a versao ${e.version}.`)):Gt(`Voce ja esta na versao mais recente (${t}).`)})}function ul(){let e=new ke;return e.name(`rock`).version(Me).description(`CLI to generate a scaffold for Rockfeller projects`),Fn(e),Cn(e),nc(e),Xc(e),kc(e),ll(e,Me),e.hook(`preAction`,async(e,t)=>{sl()&&![`update`,`setup`].includes(t.name())&&await cl(Me)}),e}await ul().parseAsync(process.argv);export{};
|