@tailor-platform/sdk 2.13.1 → 2.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/dist/{application-D3HlhR3i.mjs → application-CiN_er9X.mjs} +15 -11
- package/dist/application-CiN_er9X.mjs.map +1 -0
- package/dist/application-_8rjQRx8.mjs +1 -0
- package/dist/cli/commands/tailordb/migrate/diff-calculator.d.mts +1 -0
- package/dist/cli/lib.mjs +1 -1
- package/dist/cli/lib.mjs.map +1 -1
- package/dist/cli/main.mjs +43 -41
- package/dist/cli/main.mjs.map +1 -1
- package/dist/completion/zsh-worker.zsh +1 -1
- package/dist/configure/index.d.mts +4 -4
- package/dist/configure/index.mjs +1 -1
- package/dist/configure/index.mjs.map +1 -1
- package/dist/configure/services/tailordb/schema.d.mts +1 -1
- package/dist/configure/types/field.types.d.mts +8 -1
- package/dist/date-DrUO8rOJ.mjs +2 -0
- package/dist/date-DrUO8rOJ.mjs.map +1 -0
- package/dist/{register-ts-hook-BJmGCQAA.mjs → register-ts-hook-DS1zYiCV.mjs} +32 -32
- package/dist/register-ts-hook-DS1zYiCV.mjs.map +1 -0
- package/dist/runtime/date.d.mts +17 -0
- package/dist/runtime/index.d.mts +2 -1
- package/dist/runtime/index.mjs +1 -1
- package/dist/schema-DMlLMsWA.mjs +2 -0
- package/dist/schema-DMlLMsWA.mjs.map +1 -0
- package/dist/service-7SCy2bhm.mjs +7 -0
- package/dist/service-7SCy2bhm.mjs.map +1 -0
- package/dist/service-CWFQ8EVo.mjs +1 -0
- package/dist/types/resolver.generated.d.mts +2 -0
- package/docs/services/resolver.md +21 -0
- package/docs/services/tailordb-migration.md +25 -3
- package/docs/services/tailordb.md +2 -0
- package/package.json +2 -2
- package/dist/application-BFTkaW6X.mjs +0 -1
- package/dist/application-D3HlhR3i.mjs.map +0 -1
- package/dist/register-ts-hook-BJmGCQAA.mjs.map +0 -1
- package/dist/schema-6d_OHyZf.mjs +0 -2
- package/dist/schema-6d_OHyZf.mjs.map +0 -1
- package/dist/service-BzsSm2f6.mjs +0 -7
- package/dist/service-BzsSm2f6.mjs.map +0 -1
- package/dist/service-CmwD9bwv.mjs +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,23 @@
|
|
|
1
1
|
# @tailor-platform/sdk
|
|
2
2
|
|
|
3
|
+
## 2.14.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- [#2278](https://github.com/tailor-platform/sdk/pull/2278) [`925c6e1`](https://github.com/tailor-platform/sdk/commit/925c6e14bbb74f3ea649118e3b8b219d582d0638) Thanks [@toiroakr](https://github.com/toiroakr)! - Add `t.date({ as: "date" })` to use JavaScript Date values in resolvers. Inputs become Dates at midnight UTC, and returned Dates are formatted as YYYY-MM-DD using their UTC calendar date, including nested objects, arrays, and optional fields. Existing `t.date()` fields continue to use strings.
|
|
8
|
+
|
|
9
|
+
### Patch Changes
|
|
10
|
+
|
|
11
|
+
- [#2264](https://github.com/tailor-platform/sdk/pull/2264) [`11816e1`](https://github.com/tailor-platform/sdk/commit/11816e17b5803fa85f7e9529c0992bbfc2abb409) Thanks [@dqn](https://github.com/dqn)! - Report a member removed inside a nested field as a data-loss warning in `tailordb migration generate`, so `migration validate --strict` requires an acknowledgment; the pre-migration phase keeps the removed member readable for `migrate.ts`, a compatible member added at the same level is named as a possible rename target, and the diff output lists changed nested members
|
|
12
|
+
|
|
13
|
+
- [#2266](https://github.com/tailor-platform/sdk/pull/2266) [`b85a570`](https://github.com/tailor-platform/sdk/commit/b85a570f96598e5e90916558ec7b425291777939) Thanks [@toiroakr](https://github.com/toiroakr)! - Diagnose the "Remote migration checkpoint is not in the local migration history" error from `deploy` and `tailordb migration validate` when its specific cause is an environment that fell behind before a `migration rebaseline` ran on another environment: the message now names the migration this environment must reach and points at a concrete recovery procedure (restore the pre-rebaseline `migrations/` directory from git history, deploy against it up to that migration, then switch back and deploy again). Documented the same error and recovery procedure in the migrations troubleshooting guide.
|
|
14
|
+
|
|
15
|
+
- [#2258](https://github.com/tailor-platform/sdk/pull/2258) [`8ec7e92`](https://github.com/tailor-platform/sdk/commit/8ec7e922f5c6e5930065a70f3a906c791fff6dc4) Thanks [@dqn](https://github.com/dqn)! - Reject TailorDB enum fields that define no allowed values. `tailor deploy` and `tailor tailordb migration generate` now report an error identifying the table and field.
|
|
16
|
+
|
|
17
|
+
- [#2257](https://github.com/tailor-platform/sdk/pull/2257) [`f0405c6`](https://github.com/tailor-platform/sdk/commit/f0405c627955fc7208369d3dd5a39d35a19dd7ed) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update dependency @napi-rs/keyring to v2
|
|
18
|
+
|
|
19
|
+
- [#2262](https://github.com/tailor-platform/sdk/pull/2262) [`681a2b7`](https://github.com/tailor-platform/sdk/commit/681a2b756b4022131a2b46aadcfcdcd4d0140041) Thanks [@tailor-bobbin](https://github.com/apps/tailor-bobbin)! - `tailor workspace create --name` now reports an invalid workspace name while the command's options are parsed, instead of after the command starts running.
|
|
20
|
+
|
|
3
21
|
## 2.13.1
|
|
4
22
|
|
|
5
23
|
### Patch Changes
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{n as e}from"./brand-C8nMKhJC.mjs";import{a as t,i as n,n as r,o as i}from"./wait-point-registry-B-ESkTZX.mjs";import{t as a}from"./assert-WeXvmG4j.mjs";import{a as o,n as s,r as c}from"./logger-CCjs1DuH.mjs";import{a as l,b as u,c as d,d as f,f as p,g as m,h,l as g,m as _,n as v,o as y,p as b,s as x,t as S,u as C,x as w}from"./service-BzsSm2f6.mjs";import{t as T}from"./multiline-EyzjEwn9.mjs";import{t as E}from"./user-agent-vdHYF3QL.mjs";import{t as ee}from"./errors-BlX4gUw5.mjs";import{t as te}from"./es-builtins-BHCXINQp.mjs";import{i as D,n as ne,r as re,t as ie}from"./node-builtins-TQHhwNzG.mjs";import{t as ae}from"./type-source--ZNcV8RJ.mjs";import{createRequire as oe}from"node:module";import*as O from"pathe";import{resolve as se}from"pathe";import{resolveTSConfig as ce}from"pkg-types";import{z as k}from"zod";import{create as le}from"@bufbuild/protobuf";import*as A from"node:fs";import{readFileSync as ue}from"node:fs";import{MethodOptions_IdempotencyLevel as de}from"@bufbuild/protobuf/wkt";import{OAuth2Client as fe}from"@badgateway/oauth2-client";import{Code as j,ConnectError as M,createClient as pe}from"@connectrpc/connect";import me from"p-limit";import*as he from"node:crypto";import*as N from"rolldown";import{parseSync as P}from"oxc-parser";import{createPathsMatcher as ge,getTsconfig as _e}from"get-tsconfig";import*as F from"inflection";import*as ve from"node:os";const I=[`DEBUG`,`INFO`,`WARN`,`ERROR`,`SILENT`];function isLogLevel(e){return I.includes(e)}const ye=/^\d*[1-9]\d*$/;function parsePositiveInt(e){if(e===void 0)return;let t=e.trim();if(!ye.test(t))return;let n=Number.parseInt(t,10);return Number.isSafeInteger(n)?n:void 0}function resolveApplyConcurrency(){return parsePositiveInt(process.env.TAILOR_APPLY_CONCURRENCY)??16}function createApplyLimiter(){return me(resolveApplyConcurrency())}function byName(e,t){return e.name<t.name?-1:+(e.name>t.name)}const be=`https://api.tailor.tech`,xe=`/.well-known/oauth-authorization-server/oauth2/platform`,L=new Map;function getEnvPlatformUrl(){return process.env.TAILOR_PLATFORM_URL??process.env.PLATFORM_URL}function getEnvOAuth2ClientId(){return process.env.TAILOR_PLATFORM_OAUTH2_CLIENT_ID??process.env.PLATFORM_OAUTH2_CLIENT_ID}function normalizeBaseUrl(e){let t=new URL(e);return t.hash=``,t.search=``,t.toString().replace(/\/$/,``)}function getEffectivePlatformConfig(e={}){let t=e.platformUrl??getEnvPlatformUrl(),n=e.oauth2ClientId??getEnvOAuth2ClientId(),r=e.consoleUrl??process.env.TAILOR_PLATFORM_CONSOLE_URL,i={...t?{platformUrl:t}:{},...n?{oauth2ClientId:n}:{},...r?{consoleUrl:r}:{}};return Object.keys(i).length>0?i:void 0}function rememberPlatformConfigForToken(e,t){let n=getEffectivePlatformConfig(t);n?L.set(e,n):L.delete(e)}function getPlatformConfigForToken(e){return L.get(e)}function getPlatformBaseUrl(e={}){return normalizeBaseUrl(e.platformUrl??getEnvPlatformUrl()??`https://api.tailor.tech`)}function isDefaultPlatform(e){return getPlatformBaseUrl(e)===normalizeBaseUrl(be)}function getOAuth2ClientId(e={}){return e.oauth2ClientId??getEnvOAuth2ClientId()??`cpoc_0Iudir72fqSpqC6GQ58ri1cLAqcq5vJl`}function inferConsoleBaseUrl(e){let t=new URL(e);return t.hostname.startsWith(`api.`)?(t.hostname=t.hostname.replace(/^api\./,`console.`),normalizeBaseUrl(t.toString())):`https://console.tailor.tech`}function applyConsoleNext(e){if(o(process.env.TAILOR_CONSOLE_NEXT)!==!0)return e;let t=new URL(e);return t.hostname=t.hostname.replace(/^console\./,`console-next.`),normalizeBaseUrl(t.toString())}function getConsoleBaseUrl(e={}){if(e.consoleUrl)return normalizeBaseUrl(e.consoleUrl);if(e.platformUrl){let t=inferConsoleBaseUrl(e.platformUrl);if(t!==`https://console.tailor.tech`)return applyConsoleNext(t)}return process.env.TAILOR_PLATFORM_CONSOLE_URL?normalizeBaseUrl(process.env.TAILOR_PLATFORM_CONSOLE_URL):applyConsoleNext(inferConsoleBaseUrl(getPlatformBaseUrl(e)))}function initOAuth2Client(e){return new fe({clientId:getOAuth2ClientId(e),server:getPlatformBaseUrl(e),discoveryEndpoint:xe})}async function initOperatorClient(e,t){let n=t??getPlatformConfigForToken(e),[{createTracingInterceptor:r},{OperatorService:i}]=await Promise.all([import(`./interceptor-DQg3cR_9.mjs`),import(`./service_pb-CFVlGYdr.mjs`)]),a=[await userAgentInterceptor(),await bearerTokenInterceptor(e),retryInterceptor(),errorHandlingInterceptor(),r(),concurrencyLimitInterceptor()],o=await createTransport(getPlatformBaseUrl(n),a);return pe(i,o)}async function createTransport(e,t){let{createConnectTransport:n}=await import(`@connectrpc/connect-node`);return n({httpVersion:`2`,baseUrl:e,interceptors:t})}async function userAgentInterceptor(){let e=await E();return t=>async n=>(n.header.set(`User-Agent`,e),await t(n))}async function bearerTokenInterceptor(e){return t=>async n=>(n.header.set(`Authorization`,`Bearer ${e}`),await t(n))}function retryInterceptor(){return e=>async t=>{if(t.stream)return await e(t);let n;for(let r=0;r<Ce;r++){r>0&&await waitRetryBackoff(r);try{return await e(t)}catch(e){if(isRetrySafeCreateAlreadyExists(e,t.method.name)){if(r>0)return s.debug(`retry: ${t.method.name} returned AlreadyExists on attempt ${r+1}; treating as success (prior attempt likely committed)`),synthesizeEmptyUnaryResponse(t);let{reportCrash:n}=await import(`./crashreport-By23O2k-.mjs`);await n(e,`handledError`)}if(t.method.name!==`CreateWorkspace`&&isRetirable(e,t.method.idempotency)){n=e,s.debug(`retry: ${t.method.name} attempt ${r+1} failed with ${connectCodeName(e)}; retrying`);continue}throw e}}throw n}}function concurrencyLimitInterceptor(){let e=createApplyLimiter();return t=>async n=>n.stream?await t(n):await e(()=>t(n))}function connectCodeName(e){return e instanceof M?j[e.code]:`unknown`}const Se=new Set([`CreateAIGateway`,`CreateApplication`,`CreateAuthConnection`,`CreateAuthHook`,`CreateAuthIDPConfig`,`CreateAuthMachineUser`,`CreateAuthOAuth2Client`,`CreateAuthSCIMConfig`,`CreateAuthSCIMResource`,`CreateAuthService`,`CreateExecutorExecutor`,`CreateIdPService`,`CreatePipelineResolver`,`CreatePipelineService`,`CreateSecretManagerSecret`,`CreateSecretManagerVault`,`CreateStaticWebsite`,`CreateTailorDBGQLPermission`,`CreateTailorDBService`,`CreateTailorDBType`,`CreateTenantConfig`,`CreateUserProfileConfig`,`CreateWorkflow`,`CreateWorkflowJobFunctionExecutionPolicy`]);function isRetrySafeCreateAlreadyExists(e,t){return e instanceof M&&e.code===j.AlreadyExists&&Se.has(t)}function synthesizeEmptyUnaryResponse(e){return{stream:!1,service:e.service,method:e.method,header:new Headers,message:le(e.method.output),trailer:new Headers}}const Ce=3;function waitRetryBackoff(e){let t=500*2**(e-1)*(1+.1*(Math.random()*2-1));return new Promise(e=>setTimeout(e,t))}function isRetirable(e,t){if(!(e instanceof M))return!1;switch(e.code){case j.ResourceExhausted:case j.Unavailable:return!0;case j.Aborted:case j.Internal:return t===de.NO_SIDE_EFFECTS||t===de.IDEMPOTENT;default:return!1}}function errorHandlingInterceptor(){return e=>async t=>{try{return await e(t)}catch(e){if(e instanceof M){let{operation:n,resourceType:r}=parseMethodName(t.method.name),i=formatRequestIdentity(t.message,t.method.name);throw new M(`Failed to ${n} ${r}${i}: ${e.rawMessage}`,e.code,e.metadata)}throw e}}}function parseMethodName(e){let t=e.match(/^(Create|Update|Delete|Set|List|Get)(.+)$/);if(!t)return{operation:`perform`,resourceType:`resource`};let[,n,r]=t;return{operation:n.toLowerCase(),resourceType:r}}const we=new Set([`name`,`id`]),Te=[`Name`,`Id`,`Namespace`],Ee=`name`,De={GetMetadata:[`trn`],SetMetadata:[`trn`],AddCustomDomain:[`domain`],GetCustomDomain:[`domain`],RemoveCustomDomain:[`domain`],CreateWorkflowJobFunctionExecutionPolicy:[`executionPolicyKey`],UpdateWorkflowJobFunctionExecutionPolicy:[`executionPolicyKey`],GetWorkflowJobFunctionExecutionPolicyByKey:[`executionPolicyKey`]};function isIdentityKey(e,t){return e.startsWith(`$`)?!1:we.has(e)||Te.some(t=>e.endsWith(t))||(De[t]?.includes(e)??!1)}function formatRequestIdentity(e,t){if(typeof e!=`object`||!e)return``;let n=[];for(let[r,i]of Object.entries(e))if(typeof i==`string`&&i!==``&&isIdentityKey(r,t))n.push(`${r}: ${i}`);else if(!r.startsWith(`$`)&&typeof i==`object`&&i&&!Array.isArray(i)&&typeof i.$typeName==`string`){let e=i[Ee];typeof e==`string`&&e!==``&&n.push(`${r}.${Ee}: ${e}`)}return n.length===0?``:` (${n.join(`, `)})`}const R=1e3;async function fetchAll(e){let t=[],n=``;for(;;){let[r,i]=await e(n,R);if(t.push(...r),!i)break;n=i}return t}function isNotFoundError(e){return e instanceof M&&e.code===j.NotFound}async function fetchAllTolerant(e){return await fetchAll(async(t,n)=>{try{return await e(t,n)}catch(e){if(isNotFoundError(e))return[[],``];throw e}})}async function getOrNull(e){try{return await e()}catch(e){if(isNotFoundError(e))return;throw e}}async function fetchPaged(e,t){let n=t?.limit,r=n===void 0||n===0,i=[],a=``;for(;;){let t=r?R:Math.min(n-i.length,R);if(!r&&t<=0)break;let[o,s]=await e(a,t);if(i.push(...o),!r&&i.length>=n||!s)break;a=s}return!r&&i.length>n?i.slice(0,n):i}async function fetchUserInfo(e,t){let n=new URL(`/auth/platform/userinfo`,getPlatformBaseUrl(t)).href,r=await fetch(n,{headers:{Authorization:`Bearer ${e}`,"User-Agent":await E()}});if(!r.ok)throw Error(`Failed to fetch user info: ${r.statusText}`);let i=await r.json();return k.object({sub:k.string(),email:k.string()}).parse(i)}async function resolveStaticWebsiteUrls(e,t,n,r,i={}){if(!n)return[];let{expectedLocalNames:a}=i;return(await Promise.all(n.map(async n=>{let i=n.match(/:url(\/.*)?$/);if(i&&i.index!==void 0){let o=n.substring(0,i.index),c=i[1]||``;try{let n=await e.getStaticWebsite({workspaceId:t,name:o});return n.staticwebsite?.url?[n.staticwebsite.url+c]:(s.warn(`Static website "${o}" has no URL assigned yet. Excluding from ${r}.`),[])}catch(e){return isNotFoundError(e)&&a?.has(o)?[n]:(s.warn(`Static website "${o}" not found for ${r} configuration. Excluding from ${r}.`),[])}}return[n]}))).flat()}async function fetchMachineUserToken(e,t,n){let r=new URL(`/oauth2/token`,e).href,i=new URLSearchParams;i.append(`grant_type`,`client_credentials`),i.append(`client_id`,t),i.append(`client_secret`,n);let a={method:`POST`,headers:{"User-Agent":await E(),"Content-Type":`application/x-www-form-urlencoded`},body:i},o=await withConnectTimeoutRetry(`machine user token request`,()=>fetch(r,a));if(!o.ok){let e=await o.text().catch(()=>``);throw Error(`Failed to fetch machine user token: ${o.status} ${o.statusText} ${e.slice(0,500)}`)}let s=await o.json();return k.object({token_type:k.string(),access_token:k.string(),expires_in:k.number()}).parse(s)}function isUndiciConnectTimeout(e){if(!(e instanceof TypeError))return!1;let t=e.cause;return t instanceof Error&&`code`in t&&t.code===`UND_ERR_CONNECT_TIMEOUT`}async function withConnectTimeoutRetry(e,t){for(let n=1;;n++)try{return await t()}catch(t){if(!isUndiciConnectTimeout(t)||n>=3)throw t;s.debug(`retry: ${e} attempt ${n} failed with UND_ERR_CONNECT_TIMEOUT; retrying`),await waitRetryBackoff(n)}}async function fetchPlatformMachineUserToken(e,t,n){let r=getPlatformBaseUrl(n);return await withConnectTimeoutRetry(`platform machine user token request`,()=>new fe({clientId:e,clientSecret:t,server:r,discoveryEndpoint:xe}).clientCredentials())}async function closeConnectionPool(){let e=globalThis,t=e[Symbol.for(`undici.globalDispatcher.2`)]??e[Symbol.for(`undici.globalDispatcher.1`)];typeof t?.close==`function`&&await t.close()}function getPluginImportBaseDirs(e){return e?[O.dirname(e)]:[process.cwd()]}function resolveRelativePluginImportPath(e,t){if(!e.startsWith(`.`))return null;for(let n of t){let t=O.resolve(n,e);if(A.existsSync(t))return t}return null}function getRawPluginTableName(e){let t=typeof e==`object`&&e&&`name`in e?e.name:void 0;return typeof t==`string`?t:void 0}function getPluginGenerationDependencies(e){let t=new Set;return e.onTailorDBReady&&t.add(`tailordb`),e.onResolverReady&&t.add(`resolver`),e.onExecutorReady&&t.add(`executor`),t}function hasGenerationHooks(e){return!!(e.onTailorDBReady||e.onResolverReady||e.onExecutorReady)}function isPluginExecutorWithFile(e){return`resolve`in e&&`context`in e}function generatePluginExecutorFiles(e,t,n,r,i){if(e.length===0)return[];let a=[],o=getPluginImportBaseDirs(i);for(let i of e){let e=generateSingleExecutorFile(i,t,n,r,o);a.push(e);let l=O.relative(process.cwd(),e);s.log(` Plugin Executor File: ${c.success(l)} from plugin ${c.info(i.pluginId)}`)}return a}function generateSingleExecutorFile(e,t,n,r,i=[]){let a=sanitizePluginId$1(e.pluginId),o=O.join(t,a,`executors`);A.mkdirSync(o,{recursive:!0});let s=sanitizeExecutorFileName(e.executor.name),c=O.join(o,`${s}.ts`),l;return l=isPluginExecutorWithFile(e.executor)?generateExecutorFileContentNew(e,e.executor,t,n,r,i):generateExecutorFileContentLegacy(e.executor),A.writeFileSync(c,l),c}function generateExecutorFileContentNew(e,t,n,r,i,a=[]){let{resolve:o,context:s}=t,c=sanitizePluginId$1(e.pluginId),l=O.join(n,c,`executors`),u=resolveExecutorImportPath(o,e.pluginImportPath,l,a),d=collectTableImports(s,n,e.pluginId,r,i),f=[];for(let[,e]of d)f.push(`import { ${e.variableName} } from "${e.importPath}";`);let p=generateContextCode(s,d);return T`
|
|
1
|
+
import{n as e}from"./brand-C8nMKhJC.mjs";import{a as t,i as n,n as r,o as i}from"./wait-point-registry-B-ESkTZX.mjs";import{t as a}from"./assert-WeXvmG4j.mjs";import{a as o,n as s,r as c}from"./logger-CCjs1DuH.mjs";import{a as l,b as u,c as d,d as f,f as p,g as m,h,l as g,m as _,n as v,o as y,p as b,s as x,t as S,u as C,x as w}from"./service-7SCy2bhm.mjs";import{t as T}from"./multiline-EyzjEwn9.mjs";import{t as E}from"./user-agent-vdHYF3QL.mjs";import{t as ee}from"./errors-BlX4gUw5.mjs";import{t as te}from"./es-builtins-BHCXINQp.mjs";import{i as D,n as ne,r as re,t as ie}from"./node-builtins-TQHhwNzG.mjs";import{t as ae}from"./type-source--ZNcV8RJ.mjs";import{createRequire as oe}from"node:module";import*as O from"pathe";import{resolve as se}from"pathe";import{resolveTSConfig as ce}from"pkg-types";import{z as k}from"zod";import{create as le}from"@bufbuild/protobuf";import*as A from"node:fs";import{readFileSync as ue}from"node:fs";import{MethodOptions_IdempotencyLevel as de}from"@bufbuild/protobuf/wkt";import{OAuth2Client as fe}from"@badgateway/oauth2-client";import{Code as j,ConnectError as M,createClient as pe}from"@connectrpc/connect";import me from"p-limit";import*as he from"node:crypto";import*as N from"rolldown";import{parseSync as P}from"oxc-parser";import{createPathsMatcher as ge,getTsconfig as _e}from"get-tsconfig";import*as F from"inflection";import*as ve from"node:os";const I=[`DEBUG`,`INFO`,`WARN`,`ERROR`,`SILENT`];function isLogLevel(e){return I.includes(e)}const ye=/^\d*[1-9]\d*$/;function parsePositiveInt(e){if(e===void 0)return;let t=e.trim();if(!ye.test(t))return;let n=Number.parseInt(t,10);return Number.isSafeInteger(n)?n:void 0}function resolveApplyConcurrency(){return parsePositiveInt(process.env.TAILOR_APPLY_CONCURRENCY)??16}function createApplyLimiter(){return me(resolveApplyConcurrency())}function byName(e,t){return e.name<t.name?-1:+(e.name>t.name)}const be=`https://api.tailor.tech`,xe=`/.well-known/oauth-authorization-server/oauth2/platform`,L=new Map;function getEnvPlatformUrl(){return process.env.TAILOR_PLATFORM_URL??process.env.PLATFORM_URL}function getEnvOAuth2ClientId(){return process.env.TAILOR_PLATFORM_OAUTH2_CLIENT_ID??process.env.PLATFORM_OAUTH2_CLIENT_ID}function normalizeBaseUrl(e){let t=new URL(e);return t.hash=``,t.search=``,t.toString().replace(/\/$/,``)}function getEffectivePlatformConfig(e={}){let t=e.platformUrl??getEnvPlatformUrl(),n=e.oauth2ClientId??getEnvOAuth2ClientId(),r=e.consoleUrl??process.env.TAILOR_PLATFORM_CONSOLE_URL,i={...t?{platformUrl:t}:{},...n?{oauth2ClientId:n}:{},...r?{consoleUrl:r}:{}};return Object.keys(i).length>0?i:void 0}function rememberPlatformConfigForToken(e,t){let n=getEffectivePlatformConfig(t);n?L.set(e,n):L.delete(e)}function getPlatformConfigForToken(e){return L.get(e)}function getPlatformBaseUrl(e={}){return normalizeBaseUrl(e.platformUrl??getEnvPlatformUrl()??`https://api.tailor.tech`)}function isDefaultPlatform(e){return getPlatformBaseUrl(e)===normalizeBaseUrl(be)}function getOAuth2ClientId(e={}){return e.oauth2ClientId??getEnvOAuth2ClientId()??`cpoc_0Iudir72fqSpqC6GQ58ri1cLAqcq5vJl`}function inferConsoleBaseUrl(e){let t=new URL(e);return t.hostname.startsWith(`api.`)?(t.hostname=t.hostname.replace(/^api\./,`console.`),normalizeBaseUrl(t.toString())):`https://console.tailor.tech`}function applyConsoleNext(e){if(o(process.env.TAILOR_CONSOLE_NEXT)!==!0)return e;let t=new URL(e);return t.hostname=t.hostname.replace(/^console\./,`console-next.`),normalizeBaseUrl(t.toString())}function getConsoleBaseUrl(e={}){if(e.consoleUrl)return normalizeBaseUrl(e.consoleUrl);if(e.platformUrl){let t=inferConsoleBaseUrl(e.platformUrl);if(t!==`https://console.tailor.tech`)return applyConsoleNext(t)}return process.env.TAILOR_PLATFORM_CONSOLE_URL?normalizeBaseUrl(process.env.TAILOR_PLATFORM_CONSOLE_URL):applyConsoleNext(inferConsoleBaseUrl(getPlatformBaseUrl(e)))}function initOAuth2Client(e){return new fe({clientId:getOAuth2ClientId(e),server:getPlatformBaseUrl(e),discoveryEndpoint:xe})}async function initOperatorClient(e,t){let n=t??getPlatformConfigForToken(e),[{createTracingInterceptor:r},{OperatorService:i}]=await Promise.all([import(`./interceptor-DQg3cR_9.mjs`),import(`./service_pb-CFVlGYdr.mjs`)]),a=[await userAgentInterceptor(),await bearerTokenInterceptor(e),retryInterceptor(),errorHandlingInterceptor(),r(),concurrencyLimitInterceptor()],o=await createTransport(getPlatformBaseUrl(n),a);return pe(i,o)}async function createTransport(e,t){let{createConnectTransport:n}=await import(`@connectrpc/connect-node`);return n({httpVersion:`2`,baseUrl:e,interceptors:t})}async function userAgentInterceptor(){let e=await E();return t=>async n=>(n.header.set(`User-Agent`,e),await t(n))}async function bearerTokenInterceptor(e){return t=>async n=>(n.header.set(`Authorization`,`Bearer ${e}`),await t(n))}function retryInterceptor(){return e=>async t=>{if(t.stream)return await e(t);let n;for(let r=0;r<Ce;r++){r>0&&await waitRetryBackoff(r);try{return await e(t)}catch(e){if(isRetrySafeCreateAlreadyExists(e,t.method.name)){if(r>0)return s.debug(`retry: ${t.method.name} returned AlreadyExists on attempt ${r+1}; treating as success (prior attempt likely committed)`),synthesizeEmptyUnaryResponse(t);let{reportCrash:n}=await import(`./crashreport-By23O2k-.mjs`);await n(e,`handledError`)}if(t.method.name!==`CreateWorkspace`&&isRetirable(e,t.method.idempotency)){n=e,s.debug(`retry: ${t.method.name} attempt ${r+1} failed with ${connectCodeName(e)}; retrying`);continue}throw e}}throw n}}function concurrencyLimitInterceptor(){let e=createApplyLimiter();return t=>async n=>n.stream?await t(n):await e(()=>t(n))}function connectCodeName(e){return e instanceof M?j[e.code]:`unknown`}const Se=new Set([`CreateAIGateway`,`CreateApplication`,`CreateAuthConnection`,`CreateAuthHook`,`CreateAuthIDPConfig`,`CreateAuthMachineUser`,`CreateAuthOAuth2Client`,`CreateAuthSCIMConfig`,`CreateAuthSCIMResource`,`CreateAuthService`,`CreateExecutorExecutor`,`CreateIdPService`,`CreatePipelineResolver`,`CreatePipelineService`,`CreateSecretManagerSecret`,`CreateSecretManagerVault`,`CreateStaticWebsite`,`CreateTailorDBGQLPermission`,`CreateTailorDBService`,`CreateTailorDBType`,`CreateTenantConfig`,`CreateUserProfileConfig`,`CreateWorkflow`,`CreateWorkflowJobFunctionExecutionPolicy`]);function isRetrySafeCreateAlreadyExists(e,t){return e instanceof M&&e.code===j.AlreadyExists&&Se.has(t)}function synthesizeEmptyUnaryResponse(e){return{stream:!1,service:e.service,method:e.method,header:new Headers,message:le(e.method.output),trailer:new Headers}}const Ce=3;function waitRetryBackoff(e){let t=500*2**(e-1)*(1+.1*(Math.random()*2-1));return new Promise(e=>setTimeout(e,t))}function isRetirable(e,t){if(!(e instanceof M))return!1;switch(e.code){case j.ResourceExhausted:case j.Unavailable:return!0;case j.Aborted:case j.Internal:return t===de.NO_SIDE_EFFECTS||t===de.IDEMPOTENT;default:return!1}}function errorHandlingInterceptor(){return e=>async t=>{try{return await e(t)}catch(e){if(e instanceof M){let{operation:n,resourceType:r}=parseMethodName(t.method.name),i=formatRequestIdentity(t.message,t.method.name);throw new M(`Failed to ${n} ${r}${i}: ${e.rawMessage}`,e.code,e.metadata)}throw e}}}function parseMethodName(e){let t=e.match(/^(Create|Update|Delete|Set|List|Get)(.+)$/);if(!t)return{operation:`perform`,resourceType:`resource`};let[,n,r]=t;return{operation:n.toLowerCase(),resourceType:r}}const we=new Set([`name`,`id`]),Te=[`Name`,`Id`,`Namespace`],Ee=`name`,De={GetMetadata:[`trn`],SetMetadata:[`trn`],AddCustomDomain:[`domain`],GetCustomDomain:[`domain`],RemoveCustomDomain:[`domain`],CreateWorkflowJobFunctionExecutionPolicy:[`executionPolicyKey`],UpdateWorkflowJobFunctionExecutionPolicy:[`executionPolicyKey`],GetWorkflowJobFunctionExecutionPolicyByKey:[`executionPolicyKey`]};function isIdentityKey(e,t){return e.startsWith(`$`)?!1:we.has(e)||Te.some(t=>e.endsWith(t))||(De[t]?.includes(e)??!1)}function formatRequestIdentity(e,t){if(typeof e!=`object`||!e)return``;let n=[];for(let[r,i]of Object.entries(e))if(typeof i==`string`&&i!==``&&isIdentityKey(r,t))n.push(`${r}: ${i}`);else if(!r.startsWith(`$`)&&typeof i==`object`&&i&&!Array.isArray(i)&&typeof i.$typeName==`string`){let e=i[Ee];typeof e==`string`&&e!==``&&n.push(`${r}.${Ee}: ${e}`)}return n.length===0?``:` (${n.join(`, `)})`}const R=1e3;async function fetchAll(e){let t=[],n=``;for(;;){let[r,i]=await e(n,R);if(t.push(...r),!i)break;n=i}return t}function isNotFoundError(e){return e instanceof M&&e.code===j.NotFound}async function fetchAllTolerant(e){return await fetchAll(async(t,n)=>{try{return await e(t,n)}catch(e){if(isNotFoundError(e))return[[],``];throw e}})}async function getOrNull(e){try{return await e()}catch(e){if(isNotFoundError(e))return;throw e}}async function fetchPaged(e,t){let n=t?.limit,r=n===void 0||n===0,i=[],a=``;for(;;){let t=r?R:Math.min(n-i.length,R);if(!r&&t<=0)break;let[o,s]=await e(a,t);if(i.push(...o),!r&&i.length>=n||!s)break;a=s}return!r&&i.length>n?i.slice(0,n):i}async function fetchUserInfo(e,t){let n=new URL(`/auth/platform/userinfo`,getPlatformBaseUrl(t)).href,r=await fetch(n,{headers:{Authorization:`Bearer ${e}`,"User-Agent":await E()}});if(!r.ok)throw Error(`Failed to fetch user info: ${r.statusText}`);let i=await r.json();return k.object({sub:k.string(),email:k.string()}).parse(i)}async function resolveStaticWebsiteUrls(e,t,n,r,i={}){if(!n)return[];let{expectedLocalNames:a}=i;return(await Promise.all(n.map(async n=>{let i=n.match(/:url(\/.*)?$/);if(i&&i.index!==void 0){let o=n.substring(0,i.index),c=i[1]||``;try{let n=await e.getStaticWebsite({workspaceId:t,name:o});return n.staticwebsite?.url?[n.staticwebsite.url+c]:(s.warn(`Static website "${o}" has no URL assigned yet. Excluding from ${r}.`),[])}catch(e){return isNotFoundError(e)&&a?.has(o)?[n]:(s.warn(`Static website "${o}" not found for ${r} configuration. Excluding from ${r}.`),[])}}return[n]}))).flat()}async function fetchMachineUserToken(e,t,n){let r=new URL(`/oauth2/token`,e).href,i=new URLSearchParams;i.append(`grant_type`,`client_credentials`),i.append(`client_id`,t),i.append(`client_secret`,n);let a={method:`POST`,headers:{"User-Agent":await E(),"Content-Type":`application/x-www-form-urlencoded`},body:i},o=await withConnectTimeoutRetry(`machine user token request`,()=>fetch(r,a));if(!o.ok){let e=await o.text().catch(()=>``);throw Error(`Failed to fetch machine user token: ${o.status} ${o.statusText} ${e.slice(0,500)}`)}let s=await o.json();return k.object({token_type:k.string(),access_token:k.string(),expires_in:k.number()}).parse(s)}function isUndiciConnectTimeout(e){if(!(e instanceof TypeError))return!1;let t=e.cause;return t instanceof Error&&`code`in t&&t.code===`UND_ERR_CONNECT_TIMEOUT`}async function withConnectTimeoutRetry(e,t){for(let n=1;;n++)try{return await t()}catch(t){if(!isUndiciConnectTimeout(t)||n>=3)throw t;s.debug(`retry: ${e} attempt ${n} failed with UND_ERR_CONNECT_TIMEOUT; retrying`),await waitRetryBackoff(n)}}async function fetchPlatformMachineUserToken(e,t,n){let r=getPlatformBaseUrl(n);return await withConnectTimeoutRetry(`platform machine user token request`,()=>new fe({clientId:e,clientSecret:t,server:r,discoveryEndpoint:xe}).clientCredentials())}async function closeConnectionPool(){let e=globalThis,t=e[Symbol.for(`undici.globalDispatcher.2`)]??e[Symbol.for(`undici.globalDispatcher.1`)];typeof t?.close==`function`&&await t.close()}function getPluginImportBaseDirs(e){return e?[O.dirname(e)]:[process.cwd()]}function resolveRelativePluginImportPath(e,t){if(!e.startsWith(`.`))return null;for(let n of t){let t=O.resolve(n,e);if(A.existsSync(t))return t}return null}function getRawPluginTableName(e){let t=typeof e==`object`&&e&&`name`in e?e.name:void 0;return typeof t==`string`?t:void 0}function getPluginGenerationDependencies(e){let t=new Set;return e.onTailorDBReady&&t.add(`tailordb`),e.onResolverReady&&t.add(`resolver`),e.onExecutorReady&&t.add(`executor`),t}function hasGenerationHooks(e){return!!(e.onTailorDBReady||e.onResolverReady||e.onExecutorReady)}function isPluginExecutorWithFile(e){return`resolve`in e&&`context`in e}function generatePluginExecutorFiles(e,t,n,r,i){if(e.length===0)return[];let a=[],o=getPluginImportBaseDirs(i);for(let i of e){let e=generateSingleExecutorFile(i,t,n,r,o);a.push(e);let l=O.relative(process.cwd(),e);s.log(` Plugin Executor File: ${c.success(l)} from plugin ${c.info(i.pluginId)}`)}return a}function generateSingleExecutorFile(e,t,n,r,i=[]){let a=sanitizePluginId$1(e.pluginId),o=O.join(t,a,`executors`);A.mkdirSync(o,{recursive:!0});let s=sanitizeExecutorFileName(e.executor.name),c=O.join(o,`${s}.ts`),l;return l=isPluginExecutorWithFile(e.executor)?generateExecutorFileContentNew(e,e.executor,t,n,r,i):generateExecutorFileContentLegacy(e.executor),A.writeFileSync(c,l),c}function generateExecutorFileContentNew(e,t,n,r,i,a=[]){let{resolve:o,context:s}=t,c=sanitizePluginId$1(e.pluginId),l=O.join(n,c,`executors`),u=resolveExecutorImportPath(o,e.pluginImportPath,l,a),d=collectTableImports(s,n,e.pluginId,r,i),f=[];for(let[,e]of d)f.push(`import { ${e.variableName} } from "${e.importPath}";`);let p=generateContextCode(s,d);return T`
|
|
2
2
|
/**
|
|
3
3
|
* Auto-generated executor by plugin: ${e.pluginId}
|
|
4
4
|
* DO NOT EDIT - This file is generated by @tailor-platform/sdk
|
|
@@ -101,7 +101,7 @@ import{n as e}from"./brand-C8nMKhJC.mjs";import{a as t,i as n,n as r,o as i}from
|
|
|
101
101
|
return null;
|
|
102
102
|
}
|
|
103
103
|
return ${a};
|
|
104
|
-
})(${t})`}const Ve=makePrincipalExpr({source:`user`,normalize:!0,fields:{type:{raw:`$raw?.type`},id:`$raw.id`,workspaceId:`$raw.workspace_id ?? $raw.workspaceId`,attributes:`$raw.attribute_map ?? $raw.attributeMap ?? {}`,attributeList:`$raw.attributes ?? []`}}),firstObjectProperty=e=>{let t=P(`stringify-function.ts`,e,{sourceType:`module`});if(t.errors.length>0)return;let n=t.program.body[0],r=n?.type===`ExpressionStatement`&&n.expression.type===`ParenthesizedExpression`?n.expression.expression:void 0;return r?.type===`ObjectExpression`?r.properties[0]:void 0},stringifyFunction=e=>{let t=e.toString().trim();if(firstObjectProperty(`({m: ${t}})`))return t;let n=`({${t}})`,r=firstObjectProperty(n);if(r?.type===`Property`&&r.method&&r.computed)throw Error(`Computed-key method shorthand cannot be converted to a TailorDB script expression. Use an arrow function or function expression instead.`);if(r?.type===`Property`&&r.method&&r.value.type===`FunctionExpression`){let{async:e,generator:t}=r.value,i=n.slice(r.value.start,r.value.end);return`${e?`async `:``}function${t?`*`:``} ${i}`}return t};function formatScriptContext(e,t){return t?`${e} for ${t.tableName}.${t.fieldPath.join(`.`)}`:e===`validate`?e:`hooks`}const convertToScriptExpr=(e,t,n)=>getPrecompiledScriptExpr(e,t)||assertParsableExpression(`(${stringifyFunction(e)})(${buildHookCallArgs(t)})`,formatScriptContext(t,n)),convertTypeHookToExpr=(e,t)=>{let n=`typeHook.${t}`;return getPrecompiledScriptExpr(e,n)||assertParsableExpression(`(${stringifyFunction(e)})(${buildHookCallArgs(n)})`,`type-hook`)},convertTypeValidateToExpr=e=>getPrecompiledScriptExpr(e,`typeValidate`)||assertParsableExpression(`(${stringifyFunction(e)})(${buildHookCallArgs(`typeValidate`)})`,`type-validate`);function parseFieldConfig(e,t){let n=e.metadata,r=e.type,i=e.rawRelation;if(t&&t.fieldPath.length>1&&n.default!==void 0)throw Error(`Field "${t.fieldPath.join(`.`)}" on table "${t.tableName}": .default() cannot be used on nested inner fields`);if(t&&t.fieldPath.length>1&&n.hooks)throw Error(`Field "${t.fieldPath.join(`.`)}" on table "${t.tableName}": .hooks() cannot be used on nested inner fields`);let a=e.fields;return{type:r,...n,rawRelation:i,...r===`nested`&&a&&Object.keys(a).length>0?{fields:Object.entries(a).reduce((e,[n,r])=>(e[n]=parseFieldConfig(r,t&&{...t,fieldPath:[...t.fieldPath,n]}),e),{})}:{},validate:n.validate?.map(e=>({script:{expr:convertToScriptExpr(e,`validate`,t)},errorMessage:``})),hooks:n.hooks?{create:n.hooks.create?{expr:convertToScriptExpr(n.hooks.create,`hooks.create`,t)}:void 0,update:n.hooks.update?{expr:convertToScriptExpr(n.hooks.update,`hooks.update`,t)}:void 0}:void 0,serial:n.serial?{start:n.serial.start,maxValue:n.serial.maxValue,format:`format`in n.serial?n.serial.format:void 0}:void 0}}function isObjectPermissionFormat(e){return typeof e==`object`&&!!e&&`conditions`in e}function isSingleConditionFormat(e){return e.length>=2&&typeof e[1]==`string`}function normalizeOperand(e){if(e===null)throw Error(`Invalid permission operand: null`);if(typeof e==`object`&&!Array.isArray(e)&&`user`in e){let t=e.user;return{user:t===`id`?`_id`:t}}return e}function createPermissionNormalizer(e){function normalizeConditions(t){return t.map(t=>{let[n,r,i]=t;return[normalizeOperand(n),e[r],normalizeOperand(i)]})}function normalizeActionPermission(e){if(isObjectPermissionFormat(e)){let t=e.conditions;return{conditions:normalizeConditions(isSingleConditionFormat(t)?[t]:t),permit:e.permit?`allow`:`deny`,description:e.description}}if(!Array.isArray(e))throw Error(`Invalid permission format`);if(isSingleConditionFormat(e)){let[t,n,r,i]=[...e,!0];return{conditions:normalizeConditions([[t,n,r]]),permit:i?`allow`:`deny`}}let t=[],n=!0;for(let r of e){if(typeof r==`boolean`){n=r;continue}t.push(r)}return{conditions:normalizeConditions(t),permit:n?`allow`:`deny`}}return{normalizeConditions,normalizeActionPermission}}function hasOmittedPermit(e){return isObjectPermissionFormat(e)&&e.permit===void 0}const{normalizeConditions:He,normalizeActionPermission:Ue}=createPermissionNormalizer({"=":`eq`,"!=":`ne`,in:`in`,"not in":`nin`,hasAny:`hasAny`,"not hasAny":`nhasAny`});function normalizePermission(e){return Object.keys(e).reduce((t,n)=>(t[n]=e[n].map(e=>normalizeActionPermission(e)),t),{})}function normalizeGqlPermission(e){return e.map(e=>normalizeGqlPolicy(e))}function normalizeGqlPolicy(e){return{conditions:He(e.conditions),actions:e.actions===`all`?[`all`]:e.actions,permit:e.permit?`allow`:`deny`,description:e.description}}function parsePermissions(e){return{...e.record&&{record:normalizePermission(e.record)},...e.gql&&{gql:normalizeGqlPermission(e.gql)}}}function normalizeActionPermission(e){return Ue(e)}function findOmittedPermitRules(e){let t=[],n=e.record;if(n)for(let e of Object.keys(n))n[e].forEach((n,r)=>{hasOmittedPermit(n)&&t.push(`record.${String(e)}[${r}]`)});let r=e.gql;return r&&r.forEach((e,n)=>{e.permit===void 0&&t.push(`gql[${n}]`)}),t}function isGqlOperationsFullyDisabled(e){return e?e.create===!1&&e.update===!1&&e.delete===!1&&e.read===!1:!1}function findMissingPermissionConfig(e,t){return{missingPermission:!e.record,missingGqlPermission:!e.gql&&!isGqlOperationsFullyDisabled(t)}}function parseTypes(e,t,n){let r=createRecord(),i=new Set(Object.keys(e));for(let[t,a]of Object.entries(e))r[t]=parseTailorDBType(a,i,e,n);return buildBackwardRelationships(r,t,n),validatePluralFormUniqueness(r,t,n),r}function parseTailorDBType(e,t,n,r){let i=e.metadata,a=i.settings?.pluralForm||F.pluralize(e.name),o=formatTypeSourceLocation(getTypeSourceInfo(r,e.name)),s=createRecord(),c=createRecord();for(let[r,a]of Object.entries(e.fields)){let l={tableName:e.name,fieldName:r,allTableNames:t},u=parseFieldConfig(a,{tableName:e.name,fieldPath:[r]}),d=u.rawRelation;if(d){if(h(d,l),[`n-1`,`manyToOne`,`N-1`].includes(d.type)&&u.unique)throw Error(`Field "${r}" on table "${e.name}": cannot set unique on n-1 (manyToOne) relation. Use 1-1 (oneToOne) relation instead, or remove the unique constraint.`);let t=_(d,l,u.array);u=p(u,t)}if(u.array&&u.index)throw Error(`Field "${r}" on table "${e.name}": index cannot be set on array fields`);if(u.array&&u.unique)throw Error(`Field "${r}" on table "${e.name}": unique cannot be set on array fields`);let f={name:r,config:u},m=d?b(d,l):void 0;if(m){f.relation={...m};let t=m.forwardName;if(t.length===0)throw Error(`Forward relation name for field "${r}" on table "${e.name}"${o} cannot be empty. Use the "as" option in .relation({ toward: { as: ... } }) to specify a non-empty name.`);let a=c[t];if(a)throw Error(`Forward relation name "${t}" on table "${e.name}"${o} is duplicated between fields "${a.targetField}" and "${r}". Use the "as" option in .relation({ toward: { as: ... } }) to specify a unique name.`);if(Object.hasOwn(e.fields,t)){let n=t===r?`Forward relation name "${t}" on table "${e.name}"${o} is the same as its own relation field "${r}". Use the "as" option in .relation({ toward: { as: ... } }) to specify a different name.`:`Forward relation name "${t}" from field "${r}" on table "${e.name}"${o} conflicts with existing field "${t}". Use the "as" option in .relation({ toward: { as: ... } }) to specify a different name.`;throw Error(n)}if(Object.hasOwn(i.files,t))throw Error(`Forward relation name "${t}" from field "${r}" on table "${e.name}"${o} conflicts with files field "${t}". Use the "as" option in .relation({ toward: { as: ... } }) to specify a different name.`);let s=n[m.targetType];c[t]={name:t,targetType:m.targetType,targetField:r,sourceField:m.key,isArray:!1,description:s?.metadata.description||``}}s[r]=f}return{name:e.name,pluralForm:a,description:i.description,fields:s,forwardRelationships:c,backwardRelationships:createRecord(),settings:i.settings??{},permissions:parsePermissions(i.permissions),indexes:i.indexes,files:i.files,...i.typeHook&&{typeHookExpr:{...typeof i.typeHook.create==`function`&&{create:convertTypeHookToExpr(i.typeHook.create,`create`)},...typeof i.typeHook.update==`function`&&{update:convertTypeHookToExpr(i.typeHook.update,`update`)}}},...typeof i.typeValidate==`function`&&{typeValidateExpr:convertTypeValidateToExpr(i.typeValidate)}}}function buildBackwardRelationships(e,t,n){let r=Object.create(null);for(let t of Object.keys(e))r[t]=Object.create(null);for(let[t,n]of Object.entries(e))for(let[i,a]of Object.entries(e))for(let[e,o]of Object.entries(a.fields))if(o.relation&&o.relation.targetType===t){let s=o.relation.backwardName;if(!s){let e=F.camelize(i,!0);s=o.relation.unique?F.singularize(e):F.pluralize(e)}let c=r[t];if(c===void 0)throw Error(`backward name sources not initialized for table: ${t}`);c[s]||(c[s]=[]);let l=c[s];if(l===void 0)throw Error(`backward name sources entry not initialized for: ${s}`);l.push({sourceType:i,fieldName:e}),n.backwardRelationships[s]={name:s,targetType:i,targetField:e,sourceField:o.relation.key,isArray:!o.relation.unique,description:a.description||``}}let i=[];for(let[t,a]of Object.entries(r)){let r=e[t];if(r===void 0)throw Error(`type not found: ${t}`);let o=formatTypeSourceLocation(getTypeSourceInfo(n,t));for(let[e,s]of Object.entries(a)){if(s.length>1){let r=s.map(e=>{let t=formatTypeSourceLocation(getTypeSourceInfo(n,e.sourceType));return`${e.sourceType}.${e.fieldName}${t}`}).join(`, `);i.push(`Backward relation name "${e}" on table "${t}" is duplicated from: ${r}. Use the "backward" option in .relation() to specify unique names.`)}if(Object.hasOwn(r.fields,e)){let r=s[0];if(r===void 0)throw Error(`no source found for backward name: ${e}`);let a=formatTypeSourceLocation(getTypeSourceInfo(n,r.sourceType));i.push(`Backward relation name "${e}" from ${r.sourceType}.${r.fieldName}${a} conflicts with existing field "${e}" on table "${t}"${o}. Use the "backward" option in .relation() to specify a different name.`)}if(r.files&&Object.hasOwn(r.files,e)){let r=s[0];if(r===void 0)throw Error(`no source found for backward name: ${e}`);let a=formatTypeSourceLocation(getTypeSourceInfo(n,r.sourceType));i.push(`Backward relation name "${e}" from ${r.sourceType}.${r.fieldName}${a} conflicts with files field "${e}" on table "${t}"${o}. Use the "backward" option in .relation() to specify a different name.`)}if(Object.hasOwn(r.forwardRelationships,e)){let r=s[0];if(r===void 0)throw Error(`no source found for backward name: ${e}`);let a=formatTypeSourceLocation(getTypeSourceInfo(n,r.sourceType));i.push(`Relation name "${e}" on table "${t}"${o} is used by both a forward relationship and a backward relationship from ${r.sourceType}.${r.fieldName}${a}. Use the "as" option in .relation({ toward: { as: ... } }) or the "backward" option in .relation() to specify unique names.`)}}}if(i.length>0)throw Error(`Backward relation name conflicts detected in TailorDB service "${t}".\n${i.map(e=>` - ${e}`).join(`
|
|
104
|
+
})(${t})`}const Ve=makePrincipalExpr({source:`user`,normalize:!0,fields:{type:{raw:`$raw?.type`},id:`$raw.id`,workspaceId:`$raw.workspace_id ?? $raw.workspaceId`,attributes:`$raw.attribute_map ?? $raw.attributeMap ?? {}`,attributeList:`$raw.attributes ?? []`}}),firstObjectProperty=e=>{let t=P(`stringify-function.ts`,e,{sourceType:`module`});if(t.errors.length>0)return;let n=t.program.body[0],r=n?.type===`ExpressionStatement`&&n.expression.type===`ParenthesizedExpression`?n.expression.expression:void 0;return r?.type===`ObjectExpression`?r.properties[0]:void 0},stringifyFunction=e=>{let t=e.toString().trim();if(firstObjectProperty(`({m: ${t}})`))return t;let n=`({${t}})`,r=firstObjectProperty(n);if(r?.type===`Property`&&r.method&&r.computed)throw Error(`Computed-key method shorthand cannot be converted to a TailorDB script expression. Use an arrow function or function expression instead.`);if(r?.type===`Property`&&r.method&&r.value.type===`FunctionExpression`){let{async:e,generator:t}=r.value,i=n.slice(r.value.start,r.value.end);return`${e?`async `:``}function${t?`*`:``} ${i}`}return t};function formatScriptContext(e,t){return t?`${e} for ${t.tableName}.${t.fieldPath.join(`.`)}`:e===`validate`?e:`hooks`}const convertToScriptExpr=(e,t,n)=>getPrecompiledScriptExpr(e,t)||assertParsableExpression(`(${stringifyFunction(e)})(${buildHookCallArgs(t)})`,formatScriptContext(t,n)),convertTypeHookToExpr=(e,t)=>{let n=`typeHook.${t}`;return getPrecompiledScriptExpr(e,n)||assertParsableExpression(`(${stringifyFunction(e)})(${buildHookCallArgs(n)})`,`type-hook`)},convertTypeValidateToExpr=e=>getPrecompiledScriptExpr(e,`typeValidate`)||assertParsableExpression(`(${stringifyFunction(e)})(${buildHookCallArgs(`typeValidate`)})`,`type-validate`);function formatFieldLocation(e){return e?`Field "${e.fieldPath.join(`.`)}" on table "${e.tableName}": `:``}function parseFieldConfig(e,t){let n=e.metadata,r=e.type,i=e.rawRelation;if(t&&t.fieldPath.length>1&&n.default!==void 0)throw Error(`${formatFieldLocation(t)}.default() cannot be used on nested inner fields`);if(t&&t.fieldPath.length>1&&n.hooks)throw Error(`${formatFieldLocation(t)}.hooks() cannot be used on nested inner fields`);if(r===`enum`&&(n.allowedValues??[]).length===0)throw Error(`${formatFieldLocation(t)}enum fields must define at least one allowed value`);let a=e.fields;return{type:r,...n,rawRelation:i,...r===`nested`&&a&&Object.keys(a).length>0?{fields:Object.entries(a).reduce((e,[n,r])=>(e[n]=parseFieldConfig(r,t&&{...t,fieldPath:[...t.fieldPath,n]}),e),{})}:{},validate:n.validate?.map(e=>({script:{expr:convertToScriptExpr(e,`validate`,t)},errorMessage:``})),hooks:n.hooks?{create:n.hooks.create?{expr:convertToScriptExpr(n.hooks.create,`hooks.create`,t)}:void 0,update:n.hooks.update?{expr:convertToScriptExpr(n.hooks.update,`hooks.update`,t)}:void 0}:void 0,serial:n.serial?{start:n.serial.start,maxValue:n.serial.maxValue,format:`format`in n.serial?n.serial.format:void 0}:void 0}}function isObjectPermissionFormat(e){return typeof e==`object`&&!!e&&`conditions`in e}function isSingleConditionFormat(e){return e.length>=2&&typeof e[1]==`string`}function normalizeOperand(e){if(e===null)throw Error(`Invalid permission operand: null`);if(typeof e==`object`&&!Array.isArray(e)&&`user`in e){let t=e.user;return{user:t===`id`?`_id`:t}}return e}function createPermissionNormalizer(e){function normalizeConditions(t){return t.map(t=>{let[n,r,i]=t;return[normalizeOperand(n),e[r],normalizeOperand(i)]})}function normalizeActionPermission(e){if(isObjectPermissionFormat(e)){let t=e.conditions;return{conditions:normalizeConditions(isSingleConditionFormat(t)?[t]:t),permit:e.permit?`allow`:`deny`,description:e.description}}if(!Array.isArray(e))throw Error(`Invalid permission format`);if(isSingleConditionFormat(e)){let[t,n,r,i]=[...e,!0];return{conditions:normalizeConditions([[t,n,r]]),permit:i?`allow`:`deny`}}let t=[],n=!0;for(let r of e){if(typeof r==`boolean`){n=r;continue}t.push(r)}return{conditions:normalizeConditions(t),permit:n?`allow`:`deny`}}return{normalizeConditions,normalizeActionPermission}}function hasOmittedPermit(e){return isObjectPermissionFormat(e)&&e.permit===void 0}const{normalizeConditions:He,normalizeActionPermission:Ue}=createPermissionNormalizer({"=":`eq`,"!=":`ne`,in:`in`,"not in":`nin`,hasAny:`hasAny`,"not hasAny":`nhasAny`});function normalizePermission(e){return Object.keys(e).reduce((t,n)=>(t[n]=e[n].map(e=>normalizeActionPermission(e)),t),{})}function normalizeGqlPermission(e){return e.map(e=>normalizeGqlPolicy(e))}function normalizeGqlPolicy(e){return{conditions:He(e.conditions),actions:e.actions===`all`?[`all`]:e.actions,permit:e.permit?`allow`:`deny`,description:e.description}}function parsePermissions(e){return{...e.record&&{record:normalizePermission(e.record)},...e.gql&&{gql:normalizeGqlPermission(e.gql)}}}function normalizeActionPermission(e){return Ue(e)}function findOmittedPermitRules(e){let t=[],n=e.record;if(n)for(let e of Object.keys(n))n[e].forEach((n,r)=>{hasOmittedPermit(n)&&t.push(`record.${String(e)}[${r}]`)});let r=e.gql;return r&&r.forEach((e,n)=>{e.permit===void 0&&t.push(`gql[${n}]`)}),t}function isGqlOperationsFullyDisabled(e){return e?e.create===!1&&e.update===!1&&e.delete===!1&&e.read===!1:!1}function findMissingPermissionConfig(e,t){return{missingPermission:!e.record,missingGqlPermission:!e.gql&&!isGqlOperationsFullyDisabled(t)}}function parseTypes(e,t,n){let r=createRecord(),i=new Set(Object.keys(e));for(let[t,a]of Object.entries(e))r[t]=parseTailorDBType(a,i,e,n);return buildBackwardRelationships(r,t,n),validatePluralFormUniqueness(r,t,n),r}function parseTailorDBType(e,t,n,r){let i=e.metadata,a=i.settings?.pluralForm||F.pluralize(e.name),o=formatTypeSourceLocation(getTypeSourceInfo(r,e.name)),s=createRecord(),c=createRecord();for(let[r,a]of Object.entries(e.fields)){let l={tableName:e.name,fieldName:r,allTableNames:t},u=parseFieldConfig(a,{tableName:e.name,fieldPath:[r]}),d=u.rawRelation;if(d){if(h(d,l),[`n-1`,`manyToOne`,`N-1`].includes(d.type)&&u.unique)throw Error(`Field "${r}" on table "${e.name}": cannot set unique on n-1 (manyToOne) relation. Use 1-1 (oneToOne) relation instead, or remove the unique constraint.`);let t=_(d,l,u.array);u=p(u,t)}if(u.array&&u.index)throw Error(`Field "${r}" on table "${e.name}": index cannot be set on array fields`);if(u.array&&u.unique)throw Error(`Field "${r}" on table "${e.name}": unique cannot be set on array fields`);let f={name:r,config:u},m=d?b(d,l):void 0;if(m){f.relation={...m};let t=m.forwardName;if(t.length===0)throw Error(`Forward relation name for field "${r}" on table "${e.name}"${o} cannot be empty. Use the "as" option in .relation({ toward: { as: ... } }) to specify a non-empty name.`);let a=c[t];if(a)throw Error(`Forward relation name "${t}" on table "${e.name}"${o} is duplicated between fields "${a.targetField}" and "${r}". Use the "as" option in .relation({ toward: { as: ... } }) to specify a unique name.`);if(Object.hasOwn(e.fields,t)){let n=t===r?`Forward relation name "${t}" on table "${e.name}"${o} is the same as its own relation field "${r}". Use the "as" option in .relation({ toward: { as: ... } }) to specify a different name.`:`Forward relation name "${t}" from field "${r}" on table "${e.name}"${o} conflicts with existing field "${t}". Use the "as" option in .relation({ toward: { as: ... } }) to specify a different name.`;throw Error(n)}if(Object.hasOwn(i.files,t))throw Error(`Forward relation name "${t}" from field "${r}" on table "${e.name}"${o} conflicts with files field "${t}". Use the "as" option in .relation({ toward: { as: ... } }) to specify a different name.`);let s=n[m.targetType];c[t]={name:t,targetType:m.targetType,targetField:r,sourceField:m.key,isArray:!1,description:s?.metadata.description||``}}s[r]=f}return{name:e.name,pluralForm:a,description:i.description,fields:s,forwardRelationships:c,backwardRelationships:createRecord(),settings:i.settings??{},permissions:parsePermissions(i.permissions),indexes:i.indexes,files:i.files,...i.typeHook&&{typeHookExpr:{...typeof i.typeHook.create==`function`&&{create:convertTypeHookToExpr(i.typeHook.create,`create`)},...typeof i.typeHook.update==`function`&&{update:convertTypeHookToExpr(i.typeHook.update,`update`)}}},...typeof i.typeValidate==`function`&&{typeValidateExpr:convertTypeValidateToExpr(i.typeValidate)}}}function buildBackwardRelationships(e,t,n){let r=Object.create(null);for(let t of Object.keys(e))r[t]=Object.create(null);for(let[t,n]of Object.entries(e))for(let[i,a]of Object.entries(e))for(let[e,o]of Object.entries(a.fields))if(o.relation&&o.relation.targetType===t){let s=o.relation.backwardName;if(!s){let e=F.camelize(i,!0);s=o.relation.unique?F.singularize(e):F.pluralize(e)}let c=r[t];if(c===void 0)throw Error(`backward name sources not initialized for table: ${t}`);c[s]||(c[s]=[]);let l=c[s];if(l===void 0)throw Error(`backward name sources entry not initialized for: ${s}`);l.push({sourceType:i,fieldName:e}),n.backwardRelationships[s]={name:s,targetType:i,targetField:e,sourceField:o.relation.key,isArray:!o.relation.unique,description:a.description||``}}let i=[];for(let[t,a]of Object.entries(r)){let r=e[t];if(r===void 0)throw Error(`type not found: ${t}`);let o=formatTypeSourceLocation(getTypeSourceInfo(n,t));for(let[e,s]of Object.entries(a)){if(s.length>1){let r=s.map(e=>{let t=formatTypeSourceLocation(getTypeSourceInfo(n,e.sourceType));return`${e.sourceType}.${e.fieldName}${t}`}).join(`, `);i.push(`Backward relation name "${e}" on table "${t}" is duplicated from: ${r}. Use the "backward" option in .relation() to specify unique names.`)}if(Object.hasOwn(r.fields,e)){let r=s[0];if(r===void 0)throw Error(`no source found for backward name: ${e}`);let a=formatTypeSourceLocation(getTypeSourceInfo(n,r.sourceType));i.push(`Backward relation name "${e}" from ${r.sourceType}.${r.fieldName}${a} conflicts with existing field "${e}" on table "${t}"${o}. Use the "backward" option in .relation() to specify a different name.`)}if(r.files&&Object.hasOwn(r.files,e)){let r=s[0];if(r===void 0)throw Error(`no source found for backward name: ${e}`);let a=formatTypeSourceLocation(getTypeSourceInfo(n,r.sourceType));i.push(`Backward relation name "${e}" from ${r.sourceType}.${r.fieldName}${a} conflicts with files field "${e}" on table "${t}"${o}. Use the "backward" option in .relation() to specify a different name.`)}if(Object.hasOwn(r.forwardRelationships,e)){let r=s[0];if(r===void 0)throw Error(`no source found for backward name: ${e}`);let a=formatTypeSourceLocation(getTypeSourceInfo(n,r.sourceType));i.push(`Relation name "${e}" on table "${t}"${o} is used by both a forward relationship and a backward relationship from ${r.sourceType}.${r.fieldName}${a}. Use the "as" option in .relation({ toward: { as: ... } }) or the "backward" option in .relation() to specify unique names.`)}}}if(i.length>0)throw Error(`Backward relation name conflicts detected in TailorDB service "${t}".\n${i.map(e=>` - ${e}`).join(`
|
|
105
105
|
`)}`)}function validatePluralFormUniqueness(e,t,n){let r=[];for(let[,t]of Object.entries(e)){let e=F.camelize(t.name,!0);if(e===F.camelize(t.pluralForm,!0)){let i=formatTypeSourceLocation(getTypeSourceInfo(n,t.name));r.push(`Table "${t.name}"${i} has identical singular and plural query names "${e}". Use db.table(["${t.name}", "UniquePluralForm"], {...}) to set a unique pluralForm.`)}}let i=new Map;for(let t of Object.values(e)){let e=F.camelize(t.name,!0),n=F.camelize(t.pluralForm,!0),r=i.get(e)??[];if(r.push({tableName:t.name,kind:`singular`}),i.set(e,r),e!==n){let e=i.get(n)??[];e.push({tableName:t.name,kind:`plural`}),i.set(n,e)}}let a=[...i].filter(([,e])=>e.length>1);for(let[e,t]of a){let i=t.map(e=>{let t=formatTypeSourceLocation(getTypeSourceInfo(n,e.tableName));return`"${e.tableName}"${t} (${e.kind})`}).join(`, `);r.push(`GraphQL query field "${e}" conflicts between: ${i}`)}if(r.length>0)throw Error(`GraphQL field name conflicts detected in TailorDB service "${t}".\n${r.map(e=>` - ${e}`).join(`
|
|
106
106
|
`)}`)}function getTypeSourceInfo(e,t){return e&&Object.hasOwn(e,t)?e[t]:void 0}function formatTypeSourceLocation(e){return e?ae(e)?` (plugin: ${e.pluginId})`:` (${e.filePath})`:``}function createRecord(){return Object.create(null)}const We=new Set([`typeAnnotation`,`typeParameters`,`returnType`,`superTypeArguments`,`typeArguments`]);function collectBindingsFromPattern(e,t){switch(e.type){case`Identifier`:t.add(e.name);break;case`ObjectPattern`:for(let n of e.properties)n.type===`RestElement`?collectBindingsFromPattern(n.argument,t):collectBindingsFromPattern(n.value,t);break;case`ArrayPattern`:for(let n of e.elements)n&&(n.type===`RestElement`?collectBindingsFromPattern(n.argument,t):collectBindingsFromPattern(n,t));break;case`AssignmentPattern`:collectBindingsFromPattern(e.left,t)}}function isBindingPattern(e){return e.type!==`TSParameterProperty`}function isBoundInScope(e,t){for(let n=e;n;n=n.parent)if(n.bindings.has(t))return!0;return!1}const Ge=new Set([`!==`,`!=`]),Ke=new Set([`===`,`==`]);function staticStringValue(e){if(e.type===`Literal`&&typeof e.value==`string`)return e.value;if(e.type===`TemplateLiteral`&&e.expressions.length===0&&e.quasis.length===1)return e.quasis[0]?.value.cooked??void 0}function typeofGuardTarget(e){if(e.type!==`BinaryExpression`)return;let{left:t,right:n,operator:r}=e,[i,a]=t.type===`UnaryExpression`&&t.operator===`typeof`&&t.argument.type===`Identifier`?[t,n]:n.type===`UnaryExpression`&&n.operator===`typeof`&&n.argument.type===`Identifier`?[n,t]:[void 0,void 0];if(!i)return;let o=staticStringValue(a);if(o===void 0)return;let s=o===`undefined`;if(Ge.has(r)&&s||Ke.has(r)&&!s)return i.argument.name}function walkGuardedChain(e,t,n){return e.type===`Identifier`?e.name===t:e.type===`MemberExpression`&&walkGuardedChain(e.object,t,n)?(e.computed&&n(e.property),!0):!1}function findUndefinedReferences(e){let{program:t,errors:n}=P(`_.js`,e);if(n.length>0){let e=n.map(e=>` - ${e.message}`).join(`
|
|
107
107
|
`);throw Error(`Failed to parse code for free-variable analysis.\nParse errors:\n${e}`)}let r=[],i={bindings:new Set,parent:null},walk=e=>{if(!e)return;switch(e.type){case`VariableDeclarator`:collectBindingsFromPattern(e.id,i.bindings),walk(e.init);return;case`ImportDeclaration`:for(let t of e.specifiers)i.bindings.add(t.local.name);return;case`FunctionDeclaration`:case`FunctionExpression`:{e.type===`FunctionDeclaration`&&e.id&&i.bindings.add(e.id.name);let t={bindings:new Set,parent:i};e.type===`FunctionExpression`&&e.id&&t.bindings.add(e.id.name);for(let n of e.params)isBindingPattern(n)&&collectBindingsFromPattern(n,t.bindings);let n=i;i=t;for(let t of e.params)isBindingPattern(t)&&walk(t);walk(e.body),i=n;return}case`ArrowFunctionExpression`:{let t={bindings:new Set,parent:i};for(let n of e.params)isBindingPattern(n)&&collectBindingsFromPattern(n,t.bindings);let n=i;i=t;for(let t of e.params)isBindingPattern(t)&&walk(t);walk(e.body),i=n;return}case`ClassDeclaration`:case`ClassExpression`:e.id&&i.bindings.add(e.id.name),walk(e.superClass),walk(e.body);return;case`CatchClause`:e.param&&collectBindingsFromPattern(e.param,i.bindings),walk(e.body);return;case`MemberExpression`:walk(e.object),e.computed&&walk(e.property);return;case`UnaryExpression`:if(e.operator===`typeof`&&e.argument.type===`Identifier`)return;walk(e.argument);return;case`LogicalExpression`:{let t=e.operator===`&&`?typeofGuardTarget(e.left):void 0;if(walk(e.left),t&&walkGuardedChain(e.right,t,walk))return;walk(e.right);return}case`Property`:e.computed&&walk(e.key),walk(e.value);return;case`MethodDefinition`:case`TSAbstractMethodDefinition`:case`PropertyDefinition`:case`TSAbstractPropertyDefinition`:case`AccessorProperty`:case`TSAbstractAccessorProperty`:for(let t of e.decorators)walk(t.expression);e.computed&&walk(e.key),walk(e.value);return;case`LabeledStatement`:walk(e.body);return;case`Identifier`:r.push({name:e.name,scope:i});return}let t=e;for(let[e,n]of Object.entries(t))if(!(e===`type`||We.has(e))){if(Array.isArray(n))for(let e of n)walk(e);else n&&typeof n==`object`&&`type`in n&&walk(n)}};walk(t);let a=new Set;for(let{name:e,scope:t}of r)!isBoundInScope(t,e)&&!te.has(e)&&a.add(e);return a}function toScriptFunction(e,t){if(typeof e==`function`&&!getPrecompiledScriptExpr(e,t))return e}function collectScriptTargets(e){let t=[],collectFieldTargets=e=>{let n=e.metadata,r=toScriptFunction(n.hooks?.create,`hooks.create`);r&&t.push({fn:r,kind:`hooks.create`});let i=toScriptFunction(n.hooks?.update,`hooks.update`);i&&t.push({fn:i,kind:`hooks.update`});for(let e of n.validate??[]){let n=toScriptFunction(e,`validate`);n&&t.push({fn:n,kind:`validate`})}if(e.type===`nested`&&e.fields)for(let t of Object.values(e.fields))collectFieldTargets(t)};for(let t of Object.values(e.fields))collectFieldTargets(t);if(e.metadata.typeHook)for(let n of[`create`,`update`]){let r=`typeHook.${n}`,i=toScriptFunction(e.metadata.typeHook[n],r);i&&t.push({fn:i,kind:r})}let n=toScriptFunction(e.metadata.typeValidate,`typeValidate`);return n&&t.push({fn:n,kind:`typeValidate`}),t}function collectIdentifierNames(e){let{program:t}=P(`_.ts`,e),n=new Set,walk=e=>{if(!e||typeof e!=`object`)return;let t=e;t.type===`Identifier`&&typeof t.name==`string`&&n.add(t.name);for(let[e,n]of Object.entries(t))if(!(e===`property`&&t.type===`MemberExpression`&&!t.computed)&&!(e===`key`&&t.type===`Property`&&!t.computed)&&!We.has(e)){if(Array.isArray(n))for(let e of n)walk(e);else n&&typeof n==`object`&&`type`in n&&walk(n)}};return walk(t),n}function collectSourceBindings(e){let t=ue(e,`utf-8`),{program:n}=P(e,t),r=new Map;for(let e of n.body)if(e.type===`ImportDeclaration`){let n=e,i=t.slice(n.start,n.end);for(let e of n.specifiers)r.set(e.local.name,{name:e.local.name,sourceText:i,kind:`import`})}else if(e.type===`VariableDeclaration`){let n=e,i=t.slice(n.start,n.end);for(let e of n.declarations)e.id.type===`Identifier`&&r.set(e.id.name,{name:e.id.name,sourceText:i,kind:`declaration`})}else if(e.type===`FunctionDeclaration`){let n=e;if(n.id){let e=t.slice(n.start,n.end);r.set(n.id.name,{name:n.id.name,sourceText:e,kind:`declaration`})}}else if(e.type===`ExportNamedDeclaration`){let n=e.declaration;if(!n)continue;if(n.type===`VariableDeclaration`){let e=n,i=t.slice(e.start,e.end);for(let t of e.declarations)t.id.type===`Identifier`&&r.set(t.id.name,{name:t.id.name,sourceText:i,kind:`declaration`})}else if(n.type===`FunctionDeclaration`){let e=n;if(e.id){let n=t.slice(e.start,e.end);r.set(e.id.name,{name:e.id.name,sourceText:n,kind:`declaration`})}}}return r}function resolveNeededBindings(e,t){let n=new Set,r=new Set,i=[],a=new Set,resolveVars=e=>{for(let o of e){if(a.has(o))continue;a.add(o);let e=t.get(o);if(!e){i.push(o);continue}if(e.kind===`import`)n.add(e.sourceText);else{let n=collectIdentifierNames(e.sourceText),i=new Set;for(let e of n)e!==o&&t.has(e)&&i.add(e);resolveVars(i),r.add(e.sourceText)}}};return resolveVars(e),{imports:[...n],declarations:[...r],unresolved:i}}function buildPrecompiledExpr(e,t){return`(() => {
|
|
@@ -126,9 +126,10 @@ ${n.map(e=>` - ${e}`).join(`
|
|
|
126
126
|
const $message = $reasons.length > 0 ? "access denied: " + $reasons.join("; ") : "access denied";
|
|
127
127
|
throw new TailorErrors([{ message: $message, path: [] }]);
|
|
128
128
|
}
|
|
129
|
-
}`}function
|
|
130
|
-
|
|
131
|
-
|
|
129
|
+
}`}function buildResolverValidatedInputExpr(e){let{permission:t,defaultPermission:n}=e;return`
|
|
130
|
+
(() => {
|
|
131
|
+
${buildResolverPermissionGuardExpr(t??n)??``}
|
|
132
|
+
if (!_internalResolver.input) return context.input;
|
|
132
133
|
const result = t.object(_internalResolver.input).parse({
|
|
133
134
|
value: context.input,
|
|
134
135
|
data: context.input,
|
|
@@ -141,7 +142,8 @@ ${n.map(e=>` - ${e}`).join(`
|
|
|
141
142
|
path: issue.path ?? [],
|
|
142
143
|
})));
|
|
143
144
|
}
|
|
144
|
-
|
|
145
|
+
return result.value;
|
|
146
|
+
})()
|
|
145
147
|
`}async function bundleExecutors(e){let t=new Map,{config:n,startContext:r,additionalFiles:i=[],cache:a,inlineSourcemap:o,bundleLogLevel:l=`DEBUG`,baseDir:u,tsconfigCache:d}=e,f=[...m(n,u),...i];if(f.length===0)return s.warn(`No executor files found for patterns: ${n.files.join(`, `)}`),t;s.newline(),s.log(`Bundling ${c.highlight(f.length.toString())} files for ${c.info(`"executor"`)}`);let p=[];for(let e of f){let t=await v(e);if(!t){s.debug(` Skipping: ${e} (could not be loaded)`);continue}if(![`function`,`jobFunction`].includes(t.operation.kind)){s.debug(` Skipping: ${t.name} (not a function executor)`);continue}p.push({name:t.name,sourceFile:e})}if(p.length===0)return s.debug(` No function executors to bundle`),t;let h=await resolveTSConfigWithFallback(u),g=await withBundleConcurrency(p,e=>bundleSingleExecutor(e,h,r,a,o,l,d));for(let[e,n]of g)t.set(e,n);return s.log(`${c.success(`Bundled`)} ${c.info(`"executor"`)}`),t}async function bundleSingleExecutor(e,t,n,r,i,a=`DEBUG`,o){let s=serializeStartContext(n),c=computeBundlerContextHash({sourceFile:e.sourceFile,extraContext:s,tsconfig:t,inlineSourcemap:i,bundleLogLevel:a}),l=await withCache({cache:r,kind:`executor`,name:e.name,sourceFile:e.sourceFile,contextHash:c,async build(r,s){let c=O.resolve(e.sourceFile),l=T`
|
|
146
148
|
import _internalExecutor from "${c}";
|
|
147
149
|
|
|
@@ -170,14 +172,16 @@ ${r}
|
|
|
170
172
|
};
|
|
171
173
|
`}function buildOutputEntry(e){return`import __adapter from ${JSON.stringify(e)};
|
|
172
174
|
globalThis.transform = __adapter.output;
|
|
173
|
-
`}function rejectAsyncInBundle(e,t,n){let{program:r}=P(`${t}.${n}.bundle.js`,e),i=!1,a=[r];for(;a.length>0;){let e=a.pop();if(!e||typeof e!=`object`)continue;let t=e,n=typeof t.type==`string`?t.type:``;if(n===`AwaitExpression`){i=!0;break}if((n===`FunctionDeclaration`||n===`FunctionExpression`||n===`ArrowFunctionExpression`)&&t.async===!0){i=!0;break}if((n===`ForOfStatement`||n===`ForStatement`)&&t.await===!0){i=!0;break}for(let e of Object.keys(t)){let n=t[e];if(Array.isArray(n))for(let e of n)a.push(e);else n&&typeof n==`object`&&a.push(n)}}if(i)throw Error(`HTTP adapter "${t}" ${n} bundle contains async/await, which is unavailable in the gateway runtime. Check imported helper modules — even if your handler is synchronous, an async helper will fail at runtime.`)}function createHttpAdapterService(e){let{config:t,baseDir:n}=e,r=[],i=0,a=!1;return{config:t,get adapters(){return r},get fileCount(){return i},loadAdapters:async()=>{if(a)return;let e=await loadAdapterFiles(t,n);r=e.adapters,i=e.fileCount,a=!0},printLoadedAdapters:()=>{if(r.length!==0){s.newline(),s.log(`Found ${c.highlight(r.length.toString())} HTTP adapters`);for(let{adapter:e,sourceFile:t}of r){let n=O.relative(process.cwd(),t);s.log(`HTTP adapter: ${c.successBright(`"${e.name}"`)} loaded from ${c.path(n)}`)}}}}}async function loadAdapterFiles(e,t){if(e.files.length===0)return{adapters:[],fileCount:0};let n=m(e,t),r=await Promise.all(n.map(loadAdapterFromFile)),i=[],a=new Map;for(let e of r){if(!e)continue;let t=a.get(e.adapter.name);if(t)throw Error(`Duplicate HTTP adapter name "${e.adapter.name}" found:\n - ${t}\n - ${e.sourceFile}\nEach HTTP adapter must have a unique name.`);a.set(e.adapter.name,e.sourceFile),i.push(e)}return{adapters:i,fileCount:n.length}}async function loadAdapterFromFile(t){try{let n=await u(t);if(!e(n.default,`http-adapter`)){let t=Object.entries(n).find(([t,n])=>t!=="default"&&e(n,`http-adapter`));if(t)throw Error(`HTTP adapter must be the default export, but it is exported as \`${t[0]}\`. Re-export it: \`export default createHttpAdapter({...})\`.`);return null}let r=Xe.safeParse(n.default);if(!r.success)throw r.error;let i=r.data,a=collectMethodKeys(i);return rejectAsyncHandlers(i,a,t),{adapter:i,sourceFile:t,methods:a,hasOutput:i.output!==void 0}}catch(e){let n=O.relative(process.cwd(),t);throw s.error(`${c.error(`Failed to load HTTP adapter from`)} ${c.errorBright(n)}`),s.error(String(e)),e}}function collectMethodKeys(e){let t=e.input;return qe.filter(e=>typeof t[e]==`function`)}function rejectAsyncHandlers(e,t,n){let r=e.input;for(let i of t)if(isAsyncFunction(r[i]))throw Error(`HTTP adapter "${e.name}" in ${n} has an async \`input.${i}\` function. Handlers must be synchronous; async/await is not supported.`);if(e.output!==void 0&&isAsyncFunction(e.output))throw Error(`HTTP adapter "${e.name}" in ${n} has an async \`output\` function. Handlers must be synchronous; async/await is not supported.`)}function isAsyncFunction(e){return typeof e==`function`&&e.constructor.name===`AsyncFunction`}const et=k.union([k.literal(`query`),k.literal(`mutation`)]).describe(`GraphQL operation type`),tt=k.union([k.strictObject({user:k.string()}),k.string(),k.boolean()]),nt=k.union([k.literal(`=`),k.literal(`!=`)]),isUserOperand=e=>typeof e==`object`,rt={_loggedIn:`boolean`,id:`string`},operandTypeMismatch=(e,t)=>{if(typeof e!=`object`)return;let n=rt[e.user];if(n!==void 0&&typeof t!=`object`&&typeof t!==n)return{key:e.user,expected:n}},it=k.tuple([tt,nt,tt]).refine(([e,,t])=>isUserOperand(e)!==isUserOperand(t),"Resolver permission condition must reference a `user` operand on exactly one side (comparing two `user` operands to each other can match on `undefined === undefined`)").superRefine(([e,,t],n)=>{for(let r of[operandTypeMismatch(e,t),operandTypeMismatch(t,e)])r&&n.addIssue({code:`custom`,message:`\`${r.key}\` must compare to a ${r.expected}`})}).readonly(),at=k.strictObject({conditions:k.union([it,k.array(it).min(1,`Resolver permission policy must have at least one condition`).readonly()]),permit:k.boolean(),description:k.string().optional().describe(`Reason recorded for this policy, used in the access-denied error message`)}),ot=k.union([k.array(at).min(1,`Resolver permission must have at least one policy`).refine(e=>e.some(e=>e.permit===!0),"Resolver permission must include at least one `permit: true` policy — a policy array with only `permit: false` policies still lets any caller through by simply not authenticating, since none of the deny conditions apply to a caller with no user attributes at all").readonly(),k.literal(`allowAnonymous`)]).describe('Access requirement for this resolver, evaluated against the original caller (unaffected by `invoker`) before `body` runs. "allowAnonymous" documents that anonymous callers are allowed. Omitted (default): unchanged, anonymous callers can reach the resolver'),X=k.strictObject({operation:et.describe(`GraphQL operation type (query or mutation)`),name:k.string().describe(`Resolver name`),description:k.string().optional().describe(`Resolver description`),input:k.record(k.string(),x).optional().describe(`Input field definitions`),body:w.describe(`Resolver implementation function`),output:x.describe(`Output field definition`),publishEvents:k.boolean().optional().describe(`Enable publishing events from this resolver`),invoker:y.optional().describe(`Machine user to execute this resolver as`),permission:ot.optional()});async function loadResolver(e){let t=(await u(e)).default,n=X.safeParse(t);return n.success?n.data:null}async function bundleResolvers(e){let{namespace:t,config:n,baseDir:r,defaultPermission:i,startContext:a,cache:o,inlineSourcemap:l,bundleLogLevel:u=`DEBUG`,tsconfigCache:d}=e,f=new Map,p=m(n,r);if(p.length===0)return s.warn(`No resolver files found for patterns: ${n.files.join(`, `)}`),f;s.newline(),s.log(`Bundling ${c.highlight(p.length.toString())} files for ${c.info(`"${t}"`)}`);let h=[];for(let e of p){let t=await loadResolver(e);if(!t){s.debug(` Skipping: ${e} (could not be loaded)`);continue}h.push({name:t.name,sourceFile:e,permission:t.permission})}let g=await resolveTSConfigWithFallback(r),_=await withBundleConcurrency(h,e=>bundleSingleResolver({namespace:t,resolver:e,tsconfig:g,defaultPermission:i,startContext:a,cache:o,inlineSourcemap:l,bundleLogLevel:u,tsconfigCache:d}));for(let[e,t]of _)f.set(e,t);return s.log(`${c.success(`Bundled`)} ${c.info(`"${t}"`)}`),f}async function bundleSingleResolver(e){let{namespace:t,resolver:n,tsconfig:r,defaultPermission:i,startContext:a,cache:o,inlineSourcemap:s,bundleLogLevel:c=`DEBUG`,tsconfigCache:l}=e,u=serializeStartContext(a),d=computeBundlerContextHash({sourceFile:n.sourceFile,extraContext:JSON.stringify([u,i??null]),tsconfig:r,inlineSourcemap:s,bundleLogLevel:c}),f=await withCache({cache:o,kind:`resolver`,namespace:t,name:n.name,sourceFile:n.sourceFile,contextHash:d,async build(e,t){let o=O.resolve(n.sourceFile),u=
|
|
175
|
+
`}function rejectAsyncInBundle(e,t,n){let{program:r}=P(`${t}.${n}.bundle.js`,e),i=!1,a=[r];for(;a.length>0;){let e=a.pop();if(!e||typeof e!=`object`)continue;let t=e,n=typeof t.type==`string`?t.type:``;if(n===`AwaitExpression`){i=!0;break}if((n===`FunctionDeclaration`||n===`FunctionExpression`||n===`ArrowFunctionExpression`)&&t.async===!0){i=!0;break}if((n===`ForOfStatement`||n===`ForStatement`)&&t.await===!0){i=!0;break}for(let e of Object.keys(t)){let n=t[e];if(Array.isArray(n))for(let e of n)a.push(e);else n&&typeof n==`object`&&a.push(n)}}if(i)throw Error(`HTTP adapter "${t}" ${n} bundle contains async/await, which is unavailable in the gateway runtime. Check imported helper modules — even if your handler is synchronous, an async helper will fail at runtime.`)}function createHttpAdapterService(e){let{config:t,baseDir:n}=e,r=[],i=0,a=!1;return{config:t,get adapters(){return r},get fileCount(){return i},loadAdapters:async()=>{if(a)return;let e=await loadAdapterFiles(t,n);r=e.adapters,i=e.fileCount,a=!0},printLoadedAdapters:()=>{if(r.length!==0){s.newline(),s.log(`Found ${c.highlight(r.length.toString())} HTTP adapters`);for(let{adapter:e,sourceFile:t}of r){let n=O.relative(process.cwd(),t);s.log(`HTTP adapter: ${c.successBright(`"${e.name}"`)} loaded from ${c.path(n)}`)}}}}}async function loadAdapterFiles(e,t){if(e.files.length===0)return{adapters:[],fileCount:0};let n=m(e,t),r=await Promise.all(n.map(loadAdapterFromFile)),i=[],a=new Map;for(let e of r){if(!e)continue;let t=a.get(e.adapter.name);if(t)throw Error(`Duplicate HTTP adapter name "${e.adapter.name}" found:\n - ${t}\n - ${e.sourceFile}\nEach HTTP adapter must have a unique name.`);a.set(e.adapter.name,e.sourceFile),i.push(e)}return{adapters:i,fileCount:n.length}}async function loadAdapterFromFile(t){try{let n=await u(t);if(!e(n.default,`http-adapter`)){let t=Object.entries(n).find(([t,n])=>t!=="default"&&e(n,`http-adapter`));if(t)throw Error(`HTTP adapter must be the default export, but it is exported as \`${t[0]}\`. Re-export it: \`export default createHttpAdapter({...})\`.`);return null}let r=Xe.safeParse(n.default);if(!r.success)throw r.error;let i=r.data,a=collectMethodKeys(i);return rejectAsyncHandlers(i,a,t),{adapter:i,sourceFile:t,methods:a,hasOutput:i.output!==void 0}}catch(e){let n=O.relative(process.cwd(),t);throw s.error(`${c.error(`Failed to load HTTP adapter from`)} ${c.errorBright(n)}`),s.error(String(e)),e}}function collectMethodKeys(e){let t=e.input;return qe.filter(e=>typeof t[e]==`function`)}function rejectAsyncHandlers(e,t,n){let r=e.input;for(let i of t)if(isAsyncFunction(r[i]))throw Error(`HTTP adapter "${e.name}" in ${n} has an async \`input.${i}\` function. Handlers must be synchronous; async/await is not supported.`);if(e.output!==void 0&&isAsyncFunction(e.output))throw Error(`HTTP adapter "${e.name}" in ${n} has an async \`output\` function. Handlers must be synchronous; async/await is not supported.`)}function isAsyncFunction(e){return typeof e==`function`&&e.constructor.name===`AsyncFunction`}const et=k.union([k.literal(`query`),k.literal(`mutation`)]).describe(`GraphQL operation type`),tt=k.union([k.strictObject({user:k.string()}),k.string(),k.boolean()]),nt=k.union([k.literal(`=`),k.literal(`!=`)]),isUserOperand=e=>typeof e==`object`,rt={_loggedIn:`boolean`,id:`string`},operandTypeMismatch=(e,t)=>{if(typeof e!=`object`)return;let n=rt[e.user];if(n!==void 0&&typeof t!=`object`&&typeof t!==n)return{key:e.user,expected:n}},it=k.tuple([tt,nt,tt]).refine(([e,,t])=>isUserOperand(e)!==isUserOperand(t),"Resolver permission condition must reference a `user` operand on exactly one side (comparing two `user` operands to each other can match on `undefined === undefined`)").superRefine(([e,,t],n)=>{for(let r of[operandTypeMismatch(e,t),operandTypeMismatch(t,e)])r&&n.addIssue({code:`custom`,message:`\`${r.key}\` must compare to a ${r.expected}`})}).readonly(),at=k.strictObject({conditions:k.union([it,k.array(it).min(1,`Resolver permission policy must have at least one condition`).readonly()]),permit:k.boolean(),description:k.string().optional().describe(`Reason recorded for this policy, used in the access-denied error message`)}),ot=k.union([k.array(at).min(1,`Resolver permission must have at least one policy`).refine(e=>e.some(e=>e.permit===!0),"Resolver permission must include at least one `permit: true` policy — a policy array with only `permit: false` policies still lets any caller through by simply not authenticating, since none of the deny conditions apply to a caller with no user attributes at all").readonly(),k.literal(`allowAnonymous`)]).describe('Access requirement for this resolver, evaluated against the original caller (unaffected by `invoker`) before `body` runs. "allowAnonymous" documents that anonymous callers are allowed. Omitted (default): unchanged, anonymous callers can reach the resolver'),X=k.strictObject({operation:et.describe(`GraphQL operation type (query or mutation)`),name:k.string().describe(`Resolver name`),description:k.string().optional().describe(`Resolver description`),input:k.record(k.string(),x).optional().describe(`Input field definitions`),body:w.describe(`Resolver implementation function`),output:x.describe(`Output field definition`),publishEvents:k.boolean().optional().describe(`Enable publishing events from this resolver`),invoker:y.optional().describe(`Machine user to execute this resolver as`),permission:ot.optional()});async function loadResolver(e){let t=(await u(e)).default,n=X.safeParse(t);return n.success?n.data:null}async function bundleResolvers(e){let{namespace:t,config:n,baseDir:r,defaultPermission:i,startContext:a,cache:o,inlineSourcemap:l,bundleLogLevel:u=`DEBUG`,tsconfigCache:d}=e,f=new Map,p=m(n,r);if(p.length===0)return s.warn(`No resolver files found for patterns: ${n.files.join(`, `)}`),f;s.newline(),s.log(`Bundling ${c.highlight(p.length.toString())} files for ${c.info(`"${t}"`)}`);let h=[];for(let e of p){let t=await loadResolver(e);if(!t){s.debug(` Skipping: ${e} (could not be loaded)`);continue}h.push({name:t.name,sourceFile:e,permission:t.permission})}let g=await resolveTSConfigWithFallback(r),_=await withBundleConcurrency(h,e=>bundleSingleResolver({namespace:t,resolver:e,tsconfig:g,defaultPermission:i,startContext:a,cache:o,inlineSourcemap:l,bundleLogLevel:u,tsconfigCache:d}));for(let[e,t]of _)f.set(e,t);return s.log(`${c.success(`Bundled`)} ${c.info(`"${t}"`)}`),f}async function bundleSingleResolver(e){let{namespace:t,resolver:n,tsconfig:r,defaultPermission:i,startContext:a,cache:o,inlineSourcemap:s,bundleLogLevel:c=`DEBUG`,tsconfigCache:l}=e,u=serializeStartContext(a),d=computeBundlerContextHash({sourceFile:n.sourceFile,extraContext:JSON.stringify([u,i??null]),tsconfig:r,inlineSourcemap:s,bundleLogLevel:c}),f=await withCache({cache:o,kind:`resolver`,namespace:t,name:n.name,sourceFile:n.sourceFile,contextHash:d,async build(e,t){let o=O.resolve(n.sourceFile),u=buildResolverValidatedInputExpr({permission:n.permission,defaultPermission:i}),d=T`
|
|
174
176
|
import _internalResolver from "${o}";
|
|
175
177
|
import { t } from "@tailor-platform/sdk";
|
|
178
|
+
import { serializeDateFields } from "@tailor-platform/sdk/runtime";
|
|
176
179
|
|
|
177
180
|
const $tailor_resolver_body = async (context) => {
|
|
178
181
|
const invoker = ${q};
|
|
179
|
-
${u}
|
|
180
|
-
|
|
182
|
+
const input = ${u};
|
|
183
|
+
const result = await _internalResolver.body({ ...context, input, invoker });
|
|
184
|
+
return serializeDateFields(_internalResolver.output, result);
|
|
181
185
|
};
|
|
182
186
|
|
|
183
187
|
export { $tailor_resolver_body as main };
|
|
@@ -191,5 +195,5 @@ globalThis.transform = __adapter.output;
|
|
|
191
195
|
}
|
|
192
196
|
`,f=createVirtualEntry(`workflow-job:${e.name}`,d,`js`,u),p=safeRealpath(e.sourceFile),m=t.filter(t=>t.name!==e.name&&safeRealpath(t.sourceFile)===p).map(e=>e.exportName),h=[f.plugin,{name:`workflow-transform`,transform:{filter:{id:{include:[/\.(ts|mts|cts|js|mjs|cjs)$/]}},handler(t,n){if(!t.includes(`createWorkflowJob`)&&!t.includes(`createWorkflow`)&&!hasStartCall(t))return null;let r=t;return safeRealpath(n)===p&&(r=transformWorkflowSource(t,e.name,e.exportName,m)),hasStartCall(r)&&(r=transformStartCalls(r,i,n)),r===t?null:{code:r}}}},createTsconfigPathsPlugin({onTsconfigRead:l,cache:c}),U,...a],g=createBundleLog({tsconfig:n}),_=await N.build({input:f.input,write:!1,output:{format:`esm`,sourcemap:!o||`inline`,minify:!o||{mangle:{keepNames:!0}},codeSplitting:!1},tsconfig:n,plugins:h,treeshake:composeFunctionTreeshakeOptions([createLogLevelTreeshakeOptions(s)]),...g.options});g.assertAllResolved();let v=_.output[0].code;return assertNoForbiddenRuntimeGlobals(v,`Workflow job "${e.name}"`),v}});return[e.name,f]}const ct=k.strictObject({name:k.string().describe(`Job name (must be unique across the project)`),start:w.describe(`Start function that initiates the job`),body:w.describe(`Job implementation function`),publishEvents:k.boolean().optional().describe(`Enable publishing job execution events for this job`)}),lt=[`ms`,`s`,`m`],ut={ms:1/1e3,s:1,m:60};function durationToSeconds(e){let t=e.match(/^(\d+)(ms|s|m)$/);if(!t)return 0;let n=t[1],r=t[2];return n===void 0||r===void 0?0:parseInt(n,10)*ut[r]}const dt=k.templateLiteral([k.number().int().positive(),k.enum(lt)]),durationSchema=e=>dt.refine(t=>durationToSeconds(t)<=e,{message:`Duration must be at most ${e} seconds`}),ft=k.strictObject({maxRetries:k.number().int().min(1).max(10).describe(`Maximum number of retries (1-10)`),initialBackoff:durationSchema(3600).describe(`Initial backoff duration (e.g., '1s', '500ms', '1m', max 1h)`),maxBackoff:durationSchema(86400).describe(`Maximum backoff duration (e.g., '30s', '5m', max 24h)`),backoffMultiplier:k.number().min(1).describe(`Backoff multiplier (>= 1)`)}).refine(e=>durationToSeconds(e.initialBackoff)<=durationToSeconds(e.maxBackoff),{message:`initialBackoff must be less than or equal to maxBackoff`,path:[`initialBackoff`]}).refine(e=>durationToSeconds(e.initialBackoff)>0,{message:`initialBackoff must be greater than 0`,path:[`initialBackoff`]}),pt=k.strictObject({maxConcurrentExecutions:k.number().int().min(1).max(1e3).describe(`Maximum number of concurrent executions (1-1000)`)}),mt=k.string().regex(/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/,`Invalid execution policy name: must match [a-z0-9-] (3-63 chars; must start and end with [a-z0-9])`).describe(`Workspace-unique execution policy name embedded in the resource TRN`),ht=k.string().regex(/^[a-z0-9][a-z0-9_:.-]{0,62}[a-z0-9*]$/,`Invalid execution policy key: must match [a-z0-9_:.-] (2-64 chars; must start with [a-z0-9] and end with [a-z0-9] or a trailing '*')`).describe(`Execution policy key passed to execJobFunction's executionPolicyKey option`),gt=k.strictObject({name:mt,key:ht,concurrencyPolicy:pt.optional().describe(`Optional per-key concurrency cap for job function dispatches matching this policy`)}),_t=k.strictObject({name:k.string().describe(`Workflow name`),mainJob:ct.describe(`Main job that starts the workflow`),retryPolicy:ft.optional().describe(`Retry policy for the workflow`),concurrencyPolicy:pt.optional().describe(`Concurrency policy for the workflow`),publishEvents:k.boolean().optional().describe(`Enable publishing workflow execution events for this workflow`)});function stripRuntimeStart(t){if(!e(t,`workflow`)||typeof t!=`object`||!t||!(`start`in t))return t;let{start:n,...r}=t;return r}function createWorkflowService(e){let{config:t,baseDir:n}=e,r={},i=[],a=[],o=0,l=!1;return{config:t,get workflows(){return r},get workflowSources(){return i},get jobs(){return a},get fileCount(){return o},loadWorkflows:async()=>{if(l)return;let e=await loadAndCollectJobs(t,n);r=e.workflows,i=e.workflowSources,a=e.jobs,o=e.fileCount,l=!0},printLoadedWorkflows:()=>{if(o!==0){s.newline(),s.log(`Found ${c.highlight(o.toString())} workflow files`);for(let{workflow:e,sourceFile:t}of i){let n=O.relative(process.cwd(),t);s.log(`Workflow: ${c.successBright(`"${e.name}"`)} loaded from ${c.path(n)}`)}}}}}async function loadAndCollectJobs(e,t){let n={},r=[],i=[];if(e.files.length===0)return{workflows:n,workflowSources:r,jobs:i,fileCount:0};let a=m(e,t),o=a.length,s=new Map,c=await Promise.all(a.map(async e=>{let{jobs:t,workflow:n}=await loadFileContent(e);return{workflowFile:e,jobs:t,workflow:n}}));for(let{workflowFile:e,jobs:t,workflow:a}of c){a&&(r.push({workflow:a,sourceFile:e}),n[e]=a);for(let e of t){let t=s.get(e.name);if(t)throw Error(`Duplicate job name "${e.name}" found:\n - ${t.sourceFile} (export: ${t.exportName})\n - ${e.sourceFile} (export: ${e.exportName})\nEach job must have a unique name.`);s.set(e.name,e),i.push(e)}}return{workflows:n,workflowSources:r,jobs:i,fileCount:o}}async function loadFileContent(t){let n=[],r=null;try{let i=await u(t);for(let[a,o]of Object.entries(i)){if(a==="default"){let t=_t.safeParse(stripRuntimeStart(o));if(t.success)r=t.data;else if(e(o,[`workflow`,`workflow-job`]))throw t.error;continue}let i=ct.safeParse(o);if(i.success)n.push({name:i.data.name,exportName:a,sourceFile:t,...i.data.publishEvents===void 0?{}:{publishEvents:i.data.publishEvents}});else if(e(o,[`workflow`,`workflow-job`]))throw i.error}}catch(e){let n=O.relative(process.cwd(),t);throw s.error(`${c.error(`Failed to load workflow from`)} ${c.errorBright(n)}`),s.error(String(e)),e}return{jobs:n,workflow:r}}function getApplicationAuthNamespace(e){return e.authService?.config.name??e.config?.auth?.name}function requireApplicationAuthNamespace(e){let t=getApplicationAuthNamespace(e);if(!t)throw Error(`No Auth service configured`);return t}let Z=null;const getDistDir=()=>{let e=process.env.TAILOR_BUILD_OUTPUT_DIR;return e&&e!==Z?Z=e:Z===null&&(Z=e||`.tailor`),Z};function resolveInlineSourcemap(e){if(e!==void 0)return e;let t=o(process.env.TAILOR_INLINE_SOURCEMAP);return t===void 0||t}function resolverBundleKey(e,t){return`${e}:${t}`}const vt=k.strictObject({name:k.string().regex(/^[a-z0-9][a-z0-9-]{1,28}[a-z0-9]$/,`Must be 3-30 lowercase alphanumeric characters or hyphens`).describe(`AI Gateway name`),authNamespace:k.string().regex(/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/,`Must be 3-63 lowercase alphanumeric characters or hyphens`).optional().describe(`Auth namespace used to resolve request tokens against the workspace's auth. Defaults to the application's own auth service when omitted; omitting it without an Auth service configured is rejected.`),cors:k.array(k.string()).optional().describe("Allowed CORS origins for browser-based clients. Each entry is `*`, `http(s)://*`, `http(s)://*.example.com`, or `http(s)://app.example.com`, optionally with `:port`. Empty list disables cross-origin access.")});function normalizeIdPGqlOperations(e){return e===`query`?{create:!1,update:!1,delete:!1,read:!0,sendPasswordResetEmail:!1,requestMfaSettingsUrl:!0,unenrollMfa:!1}:e}const yt=k.union([k.literal(`query`),k.strictObject({create:k.boolean().optional().describe(`Enable _createUser mutation (default: true)`),update:k.boolean().optional().describe(`Enable _updateUser mutation (default: true)`),delete:k.boolean().optional().describe(`Enable _deleteUser mutation (default: true)`),read:k.boolean().optional().describe(`Enable _users and _user queries (default: true)`),sendPasswordResetEmail:k.boolean().optional().describe(`Enable _sendPasswordResetEmail mutation (default: true)`),requestMfaSettingsUrl:k.boolean().optional().describe(`Enable _requestMfaSettingsUrl query (default: true)`),unenrollMfa:k.boolean().optional().describe(`Enable _unenrollMfa mutation (default: true)`)})]).describe(`Configuration for GraphQL operations on IdP users.
|
|
193
197
|
All operations are enabled by default (undefined or true = enabled, false = disabled).`).transform(e=>normalizeIdPGqlOperations(e)),bt=k.enum([`en`,`ja`]).describe(`IdP UI language`),xt=k.strictObject({useNonEmailIdentifier:k.boolean().optional().describe(`Use non-email identifier for usernames`),allowSelfPasswordReset:k.boolean().optional().describe(`Allow users to reset their own passwords`),passwordRequireUppercase:k.boolean().optional().describe(`Require uppercase letters in passwords`),passwordRequireLowercase:k.boolean().optional().describe(`Require lowercase letters in passwords`),passwordRequireNonAlphanumeric:k.boolean().optional().describe(`Require non-alphanumeric characters in passwords`),passwordRequireNumeric:k.boolean().optional().describe(`Require numeric characters in passwords`),passwordMinLength:k.number().int().refine(e=>e>=6&&e<=30,{message:`passwordMinLength must be between 6 and 30`}).optional().describe(`Minimum password length (6-30)`),passwordMaxLength:k.number().int().refine(e=>e>=6&&e<=4096,{message:`passwordMaxLength must be between 6 and 4096`}).optional().describe(`Maximum password length (6-4096)`),allowedEmailDomains:k.array(k.string()).optional().describe(`Restrict registration to these email domains`),allowGoogleOauth:k.boolean().optional().describe(`Enable Google OAuth login`),allowMicrosoftOauth:k.boolean().optional().describe(`Enable Microsoft OAuth login`),disablePasswordAuth:k.boolean().optional().describe(`Disable password-based authentication`),enableMfa:k.boolean().optional().describe(`Make TOTP MFA available for users in this namespace`),requireMfa:k.boolean().optional().describe(`Require TOTP MFA enrollment and challenge for password-authenticated users (requires enableMfa)`),allowedReturnOrigins:k.array(k.string().regex(/^(https?:\/\/[a-zA-Z0-9.-]+(:[0-9]+)?|[a-z0-9][a-z0-9-]{1,61}[a-z0-9]:url)$/,`must be an http(s) origin like "https://app.example.com" (scheme + host + optional port, no path/query/fragment) or a static-website placeholder like "<name>:url"`)).optional().describe(`Application origins (scheme + host + optional port) allowed as MFA self-service return targets`),mfaIssuer:k.string().max(64,`mfaIssuer must be 64 characters or less`).optional().describe(`Label shown next to the user account in authenticator apps`)}).refine(e=>e.passwordMinLength===void 0||e.passwordMaxLength===void 0||e.passwordMinLength<=e.passwordMaxLength,{message:`passwordMinLength must be less than or equal to passwordMaxLength`,path:[`passwordMinLength`]}).refine(e=>!e.allowedEmailDomains||e.allowedEmailDomains.length===0||!e.useNonEmailIdentifier,{message:`allowedEmailDomains cannot be set when useNonEmailIdentifier is true`,path:[`allowedEmailDomains`]}).refine(e=>e.allowGoogleOauth===void 0||e.allowGoogleOauth===!1||!e.useNonEmailIdentifier,{message:`allowGoogleOauth cannot be set when useNonEmailIdentifier is true`,path:[`allowGoogleOauth`]}).refine(e=>!e.allowGoogleOauth||e.allowedEmailDomains&&e.allowedEmailDomains.length>0,{message:`allowGoogleOauth requires allowedEmailDomains to be set`,path:[`allowGoogleOauth`]}).refine(e=>!e.allowMicrosoftOauth||!e.useNonEmailIdentifier,{message:`allowMicrosoftOauth cannot be set when useNonEmailIdentifier is true`,path:[`allowMicrosoftOauth`]}).refine(e=>!e.allowMicrosoftOauth||e.allowedEmailDomains&&e.allowedEmailDomains.length>0,{message:`allowMicrosoftOauth requires allowedEmailDomains to be set`,path:[`allowMicrosoftOauth`]}).refine(e=>!e.allowMicrosoftOauth||e.disablePasswordAuth===!0,{message:`allowMicrosoftOauth requires disablePasswordAuth to be enabled`,path:[`allowMicrosoftOauth`]}).refine(e=>!e.disablePasswordAuth||e.allowGoogleOauth===!0||e.allowMicrosoftOauth===!0,{message:`disablePasswordAuth requires allowGoogleOauth or allowMicrosoftOauth to be enabled`,path:[`disablePasswordAuth`]}).refine(e=>!e.disablePasswordAuth||!e.allowSelfPasswordReset,{message:`disablePasswordAuth cannot be used with allowSelfPasswordReset`,path:[`disablePasswordAuth`]}).refine(e=>!e.requireMfa||e.enableMfa===!0,{message:`requireMfa requires enableMfa to be enabled`,path:[`requireMfa`]}).refine(e=>!e.enableMfa||e.allowedReturnOrigins&&e.allowedReturnOrigins.length>0,{message:`enableMfa requires allowedReturnOrigins to list at least one origin so MFA self-service has a valid return target`,path:[`enableMfa`]}),St=k.string().max(200,`must be 200 characters or less`).regex(/^[^\r\n]*$/,`must not contain newline characters`),Ct=k.strictObject({fromName:St.optional().describe(`Default sender display name for emails`),passwordResetSubject:St.optional().describe(`Default subject for password reset emails`)}).describe(`Namespace-level email configuration defaults`),Q=k.union([k.string(),k.boolean(),k.array(k.string()).readonly(),k.array(k.boolean()).readonly(),k.strictObject({user:k.string()}),k.strictObject({idpUser:k.enum([`id`,`name`,`disabled`])}),k.strictObject({oldIdpUser:k.enum([`id`,`name`,`disabled`])}),k.strictObject({newIdpUser:k.enum([`id`,`name`,`disabled`])})]),wt=k.enum([`=`,`!=`,`in`,`not in`]),Tt=k.tuple([Q,wt,Q]).readonly(),$=k.union([k.strictObject({conditions:k.union([Tt,k.array(Tt).readonly()]),description:k.string().optional(),permit:k.boolean().optional()}),k.tuple([Q,wt,Q]).readonly(),k.tuple([Q,wt,Q,k.boolean()]).readonly(),k.array(k.union([Tt,k.boolean()])).refine(e=>{let t=e.findIndex(e=>typeof e==`boolean`);return t===-1||t===e.length-1},{message:`Boolean permit flag must only appear at the end`}).readonly()]),Et=k.strictObject({create:k.array($).readonly(),read:k.array($).readonly(),update:k.array($).readonly(),delete:k.array($).readonly(),sendPasswordResetEmail:k.array($).readonly().optional(),unenrollMfa:k.array($).readonly().optional()}).describe(`Per-operation permission policies for IdP users`),Dt=k.strictObject({name:k.string().describe(`IdP service name`),authorization:k.union([k.literal(`insecure`),k.literal(`loggedIn`),k.strictObject({cel:k.string()})]).optional().describe(`Authorization mode for IdP API access`),clients:k.array(k.string()).describe(`OAuth2 client names that can use this IdP`),lang:bt.optional().describe(`UI language for IdP pages`),userAuthPolicy:xt.transform(e=>xt.parse(e??{})).optional().describe(`User authentication policy configuration`),publishEvents:k.boolean().optional().describe(`Enable publishing user lifecycle events`),gqlOperations:yt.optional().describe(`Configure which GraphQL operations are enabled`),emailConfig:Ct.optional().describe(`Namespace-level email configuration defaults`),permission:Et.optional().describe(`Per-operation permission policies for IdP users`)}).refine(e=>!e.userAuthPolicy?.enableMfa||e.gqlOperations?.unenrollMfa===!1||e.permission!==void 0&&e.permission.unenrollMfa!==void 0,{message:`permission.unenrollMfa must be set explicitly when userAuthPolicy.enableMfa is true (set [{ conditions: [...], permit: true }] to allow, or [] to deny all). permission itself must also be defined. The requirement is only relaxed when gqlOperations.unenrollMfa is false.`,path:[`permission`,`unenrollMfa`]}).refine(e=>!e.permission||e.userAuthPolicy?.disablePasswordAuth===!0||e.gqlOperations?.sendPasswordResetEmail===!1||e.permission.sendPasswordResetEmail!==void 0,{message:`permission.sendPasswordResetEmail must be set explicitly when password authentication is enabled (set [{ conditions: [...], permit: true }] to allow, or [] to deny; only optional when userAuthPolicy.disablePasswordAuth is true or gqlOperations.sendPasswordResetEmail is false)`,path:[`permission`,`sendPasswordResetEmail`]}),Ot=k.string().regex(/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/),kt=k.record(Ot,k.string().nullish()),At=k.strictObject({vaults:k.record(Ot,kt),options:k.strictObject({ignoreNullishValues:k.boolean()})}),jt=k.strictObject({name:k.string().describe(`Static website name`),description:k.string().optional().describe(`Static website description`),allowedIpAddresses:k.array(k.string()).optional().describe(`IP addresses allowed to access the website`),customDomains:k.array(k.string()).optional().describe(`Custom domains for the static website`)}),Mt=/^[a-z0-9]+$/,Nt=/^[A-Za-z_][A-Za-z0-9_]*$/;function checkWaitPointKey(e){let{key:r,declaredBy:a}=e,o=r.split(`-`),s=o.filter(i);if(s.length>0&&a!==`define`)return a===`property`?`Invalid wait point key "${r}": $params cannot come from a property name. Pass the key to define instead, e.g. define.for("${r}")<Payload, Result>().`:`Invalid wait point key "${r}": createWaitPoint takes its type arguments first, which stops TypeScript inferring the key as a literal, so it cannot type the $params. Declare it through createWaitPoints instead: createWaitPoints((define) => ({ myWaitPoint: define.for("${r}")<Payload, Result>() })).`;let c=new Set,l=0;for(let e of o){if(e.startsWith(`$`)){let t=e.slice(1);if(!Nt.test(t))return`Invalid wait point key "${r}": "${e}" is not a usable parameter name. Use letters, digits and underscores, starting with a letter or underscore.`;if(c.has(t))return`Invalid wait point key "${r}": parameter "$${t}" appears more than once.`;c.add(t);continue}if(e!==``){if(!Mt.test(e))return`Invalid wait point key "${r}": segment "${e}" may only contain [a-z0-9]. Wait point keys accept ${n}, with $params standing in for runtime values.`;l+=1}}if(l===0&&s.length>0)return r.startsWith(`-`)||r.endsWith(`-`)?`Invalid wait point key "${r}": must match ${n}.`:`Invalid wait point key "${r}": it needs at least one literal segment alongside its $params, otherwise the key carries no identity of its own and can collide with an unrelated wait point.`;if(s.length===0)return t.test(r)?void 0:`Invalid wait point key "${r}": must match ${n}.`;let u=o.map(e=>e.startsWith(`$`)?`0`:e).join(`-`);return u.length>63?`Wait point key "${r}" cannot fit in 63 characters: even single-character parameter values produce ${u.length}.`:t.test(u)?void 0:`Invalid wait point key "${r}": must match ${n}.`}function collectWaitPointKeyFailures(e){let t=[],n=new Set;for(let r of e){let e=`${r.declaredBy} ${r.key}`;if(n.has(e))continue;n.add(e);let i=checkWaitPointKey(r);i&&t.push(i)}return t}function defineTailorDB(e,t,n){let r=[],i=[],a=[];if(!e)return{tailorDBServices:r,externalTailorDBNamespaces:i,subgraphs:a};for(let[o,s]of Object.entries(e)){if(`external`in s)i.push(o);else{let e=createTailorDBService({namespace:o,config:C.parse(s),pluginManager:n,baseDir:t});r.push(e)}a.push({Type:`tailordb`,Name:o})}return{tailorDBServices:r,externalTailorDBNamespaces:i,subgraphs:a}}function defineResolver(e,t){let n=[],r=[];if(!e)return{resolverServices:n,subgraphs:r};for(let[i,a]of Object.entries(e)){if(!(`external`in a)){let e=createResolverService(i,a,t);n.push(e)}r.push({Type:`pipeline`,Name:i})}return{resolverServices:n,subgraphs:r}}function stripIdpProviderHelper(e){let t=e;if(typeof t.provider!=`function`)return e;let{provider:n,...r}=t;return r}function defineIdp(e){let t=[],n=[];if(!e)return{idpServices:t,subgraphs:n};let r=new Set;return e.forEach(e=>{let i=e.name;if(r.has(i))throw Error(`IdP with name "${i}" already defined.`);if(r.add(i),!(`external`in e)){let n=Dt.parse(stripIdpProviderHelper(e));t.push(n)}n.push({Type:`idp`,Name:i})}),{idpServices:t,subgraphs:n}}function defineAuth(e,t,n){let r=[];if(!e)return{authService:void 0,subgraphs:r};let i;return`external`in e||(i=createAuthService(l.parse(e),t,n)),r.push({Type:`auth`,Name:e.name}),{authService:i,subgraphs:r}}function defineExecutor(e,t,n){if(!(!e&&!n))return S({config:e??{files:[]},baseDir:t})}function defineWorkflow(e,t){if(e)return createWorkflowService({config:e,baseDir:t})}function defineHttpAdapterService(e,t){if(e)return createHttpAdapterService({config:e,baseDir:t})}function stripStaticWebsiteUrlHelper(e){let t=e;if(t.url!==`${e.name}:url`)return e;let{url:n,...r}=t;return r}function defineStaticWebsites(e){let t=[],n=new Set;return(e??[]).forEach(e=>{let r=jt.parse(stripStaticWebsiteUrlHelper(e));if(n.has(r.name))throw Error(`Static website with name "${r.name}" already defined.`);n.add(r.name),t.push(r)}),t}function defineAIGateways(e,t){let n=[],r=new Set;return(e??[]).forEach(e=>{let i=vt.parse(e);if(r.has(i.name))throw Error(`AI Gateway with name "${i.name}" already defined.`);if(r.add(i.name),i.authNamespace===void 0){if(!t)throw Error(`AI Gateway "${i.name}" has no "authNamespace" and no Auth service is configured to default to. Define an Auth service, or set "authNamespace" explicitly.`);i.authNamespace=t}n.push(i)}),n}function parseSecretManager(e){if(!e)return{secrets:[],ignoreNullishValues:!1};let t=At.parse(e),{ignoreNullishValues:n}=t.options,r=Object.entries(t.vaults).map(([e,t])=>({vaultName:e,secrets:Object.entries(t).map(([e,t])=>({name:e,value:t}))}));if(!n){for(let e of r)for(let t of e.secrets)if(t.value==null)throw Error(`Secret "${e.vaultName}/${t.name}" has no value. Use { ignoreNullishValues: true } option in defineSecretManager() to skip secrets without values.`)}return{secrets:r,ignoreNullishValues:n}}function defineServices(e,t,n){let r=defineTailorDB(e.db,t,n),i=defineResolver(e.resolver,t),a=defineIdp(e.idp),o=defineAuth(e.auth,r.tailorDBServices,r.externalTailorDBNamespaces),s=defineStaticWebsites(e.staticWebsites),c=defineAIGateways(e.aiGateways,getApplicationAuthNamespace({authService:o.authService,config:e})),{secrets:l,ignoreNullishValues:u}=parseSecretManager(e.secrets);return{tailordbResult:r,resolverResult:i,idpResult:a,authResult:o,staticWebsiteServices:s,aiGatewayServices:c,secrets:l,ignoreNullishValues:u}}function buildApplication(e){let t={name:e.config.name,id:e.config.id,config:e.config,subgraphs:[...e.tailordbResult.subgraphs,...e.resolverResult.subgraphs,...e.idpResult.subgraphs,...e.authResult.subgraphs],tailorDBServices:e.tailordbResult.tailorDBServices,externalTailorDBNamespaces:e.tailordbResult.externalTailorDBNamespaces,resolverServices:e.resolverResult.resolverServices,idpServices:e.idpResult.idpServices,authService:e.authResult.authService,executorService:e.executorService,workflowService:e.workflowService,httpAdapterService:e.httpAdapterService,staticWebsiteServices:e.staticWebsiteServices,aiGatewayServices:e.aiGatewayServices,secrets:e.secrets,ignoreNullishValues:e.ignoreNullishValues,env:e.env,get applications(){return[t]}};return t}function defineApplication(e){let{config:t,pluginManager:n}=e,r=O.dirname(t.path),i=defineServices(t,r,n),a=defineExecutor(t.executor,r,!1),o=defineWorkflow(t.workflow,r),s=defineHttpAdapterService(t.httpAdapter,r);return buildApplication({config:t,...i,executorService:a,workflowService:o,httpAdapterService:s,env:t.env??{}})}function generatePluginFilesIfNeeded(e,t,n){if(!e)return[];let r=new Map;for(let e of t){let t=e.typeSourceInfo;for(let[e,n]of Object.entries(t))n.filePath&&r.set(e,{filePath:n.filePath,exportName:n.exportName})}return e.generatePluginFiles({outputDir:O.join(getDistDir(),`plugin`),sourceTableInfoMap:r,configPath:n,tableGenerator:generatePluginTableFiles,executorGenerator:generatePluginExecutorFiles})}function assertWaitPointKeys(){let e=collectWaitPointKeyFailures(r());if(e.length!==0)throw Error(e.join(`
|
|
194
|
-
`))}async function loadApplication(e){let{config:t,pluginManager:n,bundleCache:r}=e,i=O.dirname(t.path),{tailordbResult:a,resolverResult:o,idpResult:c,authResult:l,staticWebsiteServices:u,aiGatewayServices:d,secrets:f,ignoreNullishValues:p}=defineServices(t,i,n);for(let e of a.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();assertUniqueLocalTailorDBTypeNames({tailorDBServices:a.tailorDBServices});let m=generatePluginFilesIfNeeded(n,a.tailorDBServices,t.path),h=defineExecutor(t.executor,i,m.length>0),g=defineWorkflow(t.workflow,i);g&&await g.loadWorkflows();let _=defineHttpAdapterService(t.httpAdapter,i);_&&await _.loadAdapters();let v=await buildStartContext(t.workflow,getApplicationAuthNamespace({authService:l.authService,config:t}),i),y=resolveInlineSourcemap(t.inlineSourcemap),b=resolveBundleLogLevel(t.logLevel),x=createTsconfigLookupCache(),S={resolvers:new Map,executors:new Map,workflowJobs:new Map,authHooks:new Map};for(let e of o.resolverServices){let t=await bundleResolvers({namespace:e.namespace,config:e.config,baseDir:i,defaultPermission:e.defaultPermission,startContext:v,cache:r,inlineSourcemap:y,bundleLogLevel:b,tsconfigCache:x});for(let[n,r]of t)S.resolvers.set(resolverBundleKey(e.namespace,n),r)}h&&(S.executors=await bundleExecutors({config:h.config,startContext:v,additionalFiles:[...m],cache:r,inlineSourcemap:y,bundleLogLevel:b,baseDir:i,tsconfigCache:x}));let C;if(g&&g.jobs.length>0){let e=g.workflowSources.map(e=>e.workflow.mainJob.name);C=await bundleWorkflowJobs(g.jobs,e,t.env??{},v,i,r,y,b,x),S.workflowJobs=C.bundledCode}let w;if(_&&_.adapters.length>0&&(w=await bundleHttpAdapters(_.adapters.map(e=>({name:e.adapter.name,sourceFile:e.sourceFile,methods:e.methods,hasOutput:e.hasOutput})),i,r,b,x)),l.authService?.config.hooks?.beforeLogin){let e=l.authService.config.name;S.authHooks=await bundleAuthHooks({configPath:t.path,authName:e,handlerAccessPath:`auth.hooks.beforeLogin.handler`,env:t.env??{},startContext:v,cache:r,inlineSourcemap:y,bundleLogLevel:b,baseDir:i,tsconfigCache:x})}for(let e of o.resolverServices)await e.loadResolvers();return h&&(await h.loadExecutors(),m.length>0&&await h.loadPluginExecutorFiles([...m])),assertWaitPointKeys(),g&&g.printLoadedWorkflows(),_&&_.printLoadedAdapters(),s.newline(),{application:buildApplication({config:t,tailordbResult:a,resolverResult:o,idpResult:c,authResult:l,executorService:h,workflowService:g,httpAdapterService:_,staticWebsiteServices:u,aiGatewayServices:d,secrets:f,ignoreNullishValues:p,env:t.env??{}}),workflowBuildResult:C,httpAdapterBuildResult:w,bundledScripts:S}}export{isDefaultPlatform as $,createLogLevelTreeshakeOptions as A,be as B,Ve as C,resolveTSConfigWithFallback as D,createTsconfigPathsPlugin as E,hashFile as F,fetchPlatformMachineUserToken as G,fetchAllTolerant as H,getPluginGenerationDependencies as I,getOAuth2ClientId as J,fetchUserInfo as K,getRawPluginTableName as L,createBundleLog as M,createBundleCache as N,U as O,hashContent as P,initOperatorClient as Q,hasGenerationHooks as R,stringifyFunction as S,createGeneratedEntryResolverPlugin as T,fetchMachineUserToken as U,fetchAll as V,fetchPaged as W,getPlatformBaseUrl as X,getOrNull as Y,initOAuth2Client as Z,
|
|
195
|
-
//# sourceMappingURL=application-
|
|
198
|
+
`))}async function loadApplication(e){let{config:t,pluginManager:n,bundleCache:r}=e,i=O.dirname(t.path),{tailordbResult:a,resolverResult:o,idpResult:c,authResult:l,staticWebsiteServices:u,aiGatewayServices:d,secrets:f,ignoreNullishValues:p}=defineServices(t,i,n);for(let e of a.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();assertUniqueLocalTailorDBTypeNames({tailorDBServices:a.tailorDBServices});let m=generatePluginFilesIfNeeded(n,a.tailorDBServices,t.path),h=defineExecutor(t.executor,i,m.length>0),g=defineWorkflow(t.workflow,i);g&&await g.loadWorkflows();let _=defineHttpAdapterService(t.httpAdapter,i);_&&await _.loadAdapters();let v=await buildStartContext(t.workflow,getApplicationAuthNamespace({authService:l.authService,config:t}),i),y=resolveInlineSourcemap(t.inlineSourcemap),b=resolveBundleLogLevel(t.logLevel),x=createTsconfigLookupCache(),S={resolvers:new Map,executors:new Map,workflowJobs:new Map,authHooks:new Map};for(let e of o.resolverServices){let t=await bundleResolvers({namespace:e.namespace,config:e.config,baseDir:i,defaultPermission:e.defaultPermission,startContext:v,cache:r,inlineSourcemap:y,bundleLogLevel:b,tsconfigCache:x});for(let[n,r]of t)S.resolvers.set(resolverBundleKey(e.namespace,n),r)}h&&(S.executors=await bundleExecutors({config:h.config,startContext:v,additionalFiles:[...m],cache:r,inlineSourcemap:y,bundleLogLevel:b,baseDir:i,tsconfigCache:x}));let C;if(g&&g.jobs.length>0){let e=g.workflowSources.map(e=>e.workflow.mainJob.name);C=await bundleWorkflowJobs(g.jobs,e,t.env??{},v,i,r,y,b,x),S.workflowJobs=C.bundledCode}let w;if(_&&_.adapters.length>0&&(w=await bundleHttpAdapters(_.adapters.map(e=>({name:e.adapter.name,sourceFile:e.sourceFile,methods:e.methods,hasOutput:e.hasOutput})),i,r,b,x)),l.authService?.config.hooks?.beforeLogin){let e=l.authService.config.name;S.authHooks=await bundleAuthHooks({configPath:t.path,authName:e,handlerAccessPath:`auth.hooks.beforeLogin.handler`,env:t.env??{},startContext:v,cache:r,inlineSourcemap:y,bundleLogLevel:b,baseDir:i,tsconfigCache:x})}for(let e of o.resolverServices)await e.loadResolvers();return h&&(await h.loadExecutors(),m.length>0&&await h.loadPluginExecutorFiles([...m])),assertWaitPointKeys(),g&&g.printLoadedWorkflows(),_&&_.printLoadedAdapters(),s.newline(),{application:buildApplication({config:t,tailordbResult:a,resolverResult:o,idpResult:c,authResult:l,executorService:h,workflowService:g,httpAdapterService:_,staticWebsiteServices:u,aiGatewayServices:d,secrets:f,ignoreNullishValues:p,env:t.env??{}}),workflowBuildResult:C,httpAdapterBuildResult:w,bundledScripts:S}}export{isDefaultPlatform as $,createLogLevelTreeshakeOptions as A,be as B,Ve as C,resolveTSConfigWithFallback as D,createTsconfigPathsPlugin as E,hashFile as F,fetchPlatformMachineUserToken as G,fetchAllTolerant as H,getPluginGenerationDependencies as I,getOAuth2ClientId as J,fetchUserInfo as K,getRawPluginTableName as L,createBundleLog as M,createBundleCache as N,U as O,hashContent as P,initOperatorClient as Q,hasGenerationHooks as R,stringifyFunction as S,createGeneratedEntryResolverPlugin as T,fetchMachineUserToken as U,fetchAll as V,fetchPaged as W,getPlatformBaseUrl as X,getOrNull as Y,initOAuth2Client as Z,buildResolverValidatedInputExpr as _,resolveInlineSourcemap as a,createApplyLimiter as at,createPermissionNormalizer as b,requireApplicationAuthNamespace as c,resolveResolverDefaultPermissionForFile as d,isNotFoundError as et,X as f,buildResolverOperationHookExpr as g,buildExecutorArgsExpr as h,resolverBundleKey as i,byName as it,resolveBundleLogLevel as j,composeFunctionTreeshakeOptions as k,gt as l,q as m,generatePluginFilesIfNeeded as n,rememberPlatformConfigForToken as nt,getDistDir as o,I as ot,Y as p,getConsoleBaseUrl as q,loadApplication as r,resolveStaticWebsiteUrls as rt,getApplicationAuthNamespace as s,defineApplication as t,normalizeBaseUrl as tt,ct as u,assertUniqueLocalTailorDBTypeNames as v,G as w,hasOmittedPermit as x,assertUniqueTailorDBTypeNamesWithExternal as y,closeConnectionPool as z};
|
|
199
|
+
//# sourceMappingURL=application-CiN_er9X.mjs.map
|