@protobase/server 0.123.5 → 0.123.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/locale/en.js CHANGED
@@ -58,6 +58,7 @@ var en_default = {
58
58
  "disconnected": "The connected account was disconnected: its owner connects it again",
59
59
  "subscriptionNotEnded": "The subscription could not be ended at the provider: {reason}"
60
60
  },
61
+ "workflows/ready": { "tenantless": "{resource} has no tenant field, so its changes never reach a workflow of a tenant: give it .tenant(...)" },
61
62
  "mail/unsubscribe": {
62
63
  "title": "Unsubscribe",
63
64
  "question": "Stop sending {topic} mail to {recipient}?",
package/dist/locale/nl.js CHANGED
@@ -58,6 +58,7 @@ var nl_default = {
58
58
  "disconnected": "Het gekoppelde account is ontkoppeld: de eigenaar koppelt het opnieuw",
59
59
  "subscriptionNotEnded": "Het abonnement kon niet worden beëindigd bij de provider: {reason}"
60
60
  },
61
+ "workflows/ready": { "tenantless": "{resource} heeft geen tenantveld, dus zijn wijzigingen bereiken nooit een workflow van een tenant: geef het .tenant(...)" },
61
62
  "mail/unsubscribe": {
62
63
  "title": "Afmelden",
63
64
  "question": "Geen {topic}-mail meer sturen naar {recipient}?",
package/dist/package.js CHANGED
@@ -1,4 +1,4 @@
1
1
  //#region package.json
2
- var version = "0.123.5";
2
+ var version = "0.123.6";
3
3
  //#endregion
4
4
  export { version };
@@ -11,13 +11,13 @@ import { CatalogTemplate, CheckOptions, TypeEntry } from "@protobase/workflows";
11
11
  //#region src/workflows/mcp/workflow-read-tools.d.ts
12
12
  /**
13
13
  * The app's types, which the tools list and check definitions against: `checkWith` checks against the resources it is
14
- * given, so a check names only what its caller may read.
14
+ * given, so a check names only what its caller may read, and as for a workflow of a tenant when `tenanted`.
15
15
  */
16
16
  export type WorkflowCatalog = {
17
17
  types: readonly TypeEntry[];
18
18
  /** The app's email templates, whose data `app:mail.template` takes; none without it. */
19
19
  templates?: readonly CatalogTemplate[];
20
- checkWith: (models: (name: string) => ResourceModel | undefined) => CheckOptions;
20
+ checkWith: (models: (name: string) => ResourceModel | undefined, tenanted?: boolean) => CheckOptions;
21
21
  /** The custom step types of a tenant, which follow the app's types in the list and the check; none without it. */
22
22
  customTypes?: (tenant: unknown) => Promise<TypeEntry[]>;
23
23
  /** Issues a workflow's webhook URL as the caller, for `new_webhook_url` and `create_workflow` with `publish`. */
@@ -98,7 +98,7 @@ const checked = async (given, args, catalog, context) => {
98
98
  const { models } = await context.resources();
99
99
  const definition = definitionFromParts(fields);
100
100
  const custom = await customOf(catalog, context);
101
- const problems = checkDefinition(withStepsToCheck(definition), custom.check(catalog.checkWith((name) => models.find((model) => model.name === name))));
101
+ const problems = checkDefinition(withStepsToCheck(definition), custom.check(catalog.checkWith((name) => models.find((model) => model.name === name), context.session.tenant != null)));
102
102
  if (problems.length > 0) return JSON.stringify({
103
103
  valid: false,
104
104
  problems
@@ -1,4 +1,5 @@
1
1
  import { isCaptured } from "../../changes/capture-sql.js";
2
+ import { messages } from "../../locale/messages.js";
2
3
  import { readyWhen, timeField } from "./ready-when.js";
3
4
  import { checkFilter, parseFilter } from "@protobase/schema";
4
5
  //#region src/workflows/ready/ready-check.ts
@@ -9,12 +10,19 @@ const usesSearch = (node) => {
9
10
  if (kind === "search" || kind === "similar") return true;
10
11
  return Object.values(node).some(usesSearch);
11
12
  };
13
+ const catalogue = messages("workflows/ready");
14
+ /**
15
+ * Why a ready trigger of a tenant's workflow never fires on a resource without a tenant field, in the app's language,
16
+ * else English: its changes carry no tenant, so none matches the trigger's.
17
+ */
18
+ const tenantlessMessage = (resource, locale = "en") => catalogue(locale)("tenantless", { resource });
12
19
  /**
13
20
  * Why a ready trigger cannot run on the app's resources, checked as a workflow is saved: a resource that records no
14
- * changes (so no write reaches the trigger), a `when` that does not check against it (a field that is not indexed for
15
- * filtering among them, as for list filters), `now()` outside a time term, and key fields it does not have.
21
+ * changes (so no write reaches the trigger), one without a tenant field for a tenant's workflow (`tenanted`), a `when`
22
+ * that does not check against it (a field that is not indexed for filtering among them, as for list filters), `now()`
23
+ * outside a time term, and key fields it does not have.
16
24
  */
17
- const readyProblems = (models, spec) => {
25
+ const readyProblems = (models, spec, tenanted = false, locale) => {
18
26
  const model = models(spec.resource);
19
27
  if (!model) return [{
20
28
  field: "resource",
@@ -25,6 +33,10 @@ const readyProblems = (models, spec) => {
25
33
  field: "resource",
26
34
  message: `${spec.resource} records no changes, so no write reaches a trigger: declare events on it`
27
35
  });
36
+ if (tenanted && !model.tenant) problems.push({
37
+ field: "resource",
38
+ message: tenantlessMessage(spec.resource, locale)
39
+ });
28
40
  for (const name of spec.key ?? []) {
29
41
  const field = model.fields[name];
30
42
  if (!field) problems.push({
@@ -59,4 +71,4 @@ const readyProblems = (models, spec) => {
59
71
  return problems;
60
72
  };
61
73
  //#endregion
62
- export { readyProblems };
74
+ export { readyProblems, tenantlessMessage };
@@ -1,6 +1,7 @@
1
1
  import { HttpProblem } from "../../problem.js";
2
2
  import { assistantRecords } from "../../assistant/records.js";
3
3
  import { startWorkflow } from "../start-workflow.js";
4
+ import { tenantlessMessage } from "./ready-check.js";
4
5
  import { saverSession } from "../plugin-records.js";
5
6
  import { triggerFailed, triggerRecovered } from "../triggers/trigger-row.js";
6
7
  import { encodeKey } from "@protobase/schema/internal";
@@ -41,11 +42,15 @@ const orRefusal = (work) => work.then((value) => ({ value }), (error) => {
41
42
  if (reason === void 0) throw error;
42
43
  return { refused: reason };
43
44
  });
44
- /** What a ready trigger works on: its declaration, resource, and the records API as the user who saved its version. */
45
- const readyContext = async ({ deps, roles, declared }, trigger) => {
45
+ /**
46
+ * What a ready trigger works on: its declaration, resource, and the records API as the user who saved its version; or,
47
+ * for a tenant's trigger on a resource without a tenant field, why it never fires.
48
+ */
49
+ const readyContext = async ({ deps, roles, declared, locale }, trigger) => {
46
50
  const spec = declared(trigger.type)?.ready(trigger.input);
47
51
  const model = spec && deps().registry.find(spec.resource)?.model;
48
52
  if (!spec || !model) return;
53
+ if (trigger.tenant_id !== null && !model.tenant) return { tenantless: tenantlessMessage(spec.resource, locale) };
49
54
  const session = await saverSession(roles, trigger.saved_by, trigger.tenant_id ?? void 0);
50
55
  return {
51
56
  spec,
@@ -57,7 +62,7 @@ const readyContext = async ({ deps, roles, declared }, trigger) => {
57
62
  * Starts a run of the record if it is ready now: one read of it through the API as the user who saved the enabled
58
63
  * version, so their access rules, tenant scope and field access decide what the run sees, `when` evaluated on what they
59
64
  * read, then one keyed insert, so a record starts once per ready key. A record that is gone, or that they may not read,
60
- * starts nothing; a refused saver, or a key field they cannot read, marks the trigger failing, and a failing trigger
65
+ * starts nothing; a refused saver, a resource without a tenant field for a tenant's trigger, or a key field they cannot read, marks the trigger failing, and a failing trigger
61
66
  * that reads a record is active again. Answers whether this check brought the trigger back, so its records are passed
62
67
  * over again for what it missed.
63
68
  */
@@ -67,6 +72,7 @@ const startIfReady = async (input, db, trigger, key) => {
67
72
  if ("refused" in found) return failed(found.refused);
68
73
  const context = found.value;
69
74
  if (!context) return false;
75
+ if (context.tenantless !== void 0) return triggerFailed(db, input.schema, trigger, "no_tenant", context.tenantless).then(() => false);
70
76
  const { spec, model, records } = context;
71
77
  const keyValues = model.primaryKey.map((name) => key[name]);
72
78
  const got = await orRefusal(records.get(spec.resource, keyValues.length === 1 ? keyValues[0] : keyValues).catch((error) => {
@@ -54,7 +54,7 @@ const refuseProblems = (definition, types) => {
54
54
  };
55
55
  /**
56
56
  * Checks a workflow's definition on every save that changes it against the language's schema and the named-reads
57
- * profile, with the trigger and step types the app has, and keeps a changed definition as the version the table's
57
+ * profile, with the trigger and step types the app has for the workflow's tenant (`checkFor`), and keeps a changed definition as the version the table's
58
58
  * trigger numbered, saved by the caller, with the layout it has then. A save that moves only nodes checks and keeps nothing. A save leaves what is published alone: a write that sets `enabled_version`
59
59
  * publishes that saved version, checked again, and puts the workflow's trigger on it, and clearing it turns the
60
60
  * workflow off, which never depends on a definition still checking, as after an app update removed a plugin. A refusal is a 400
@@ -63,7 +63,7 @@ const refuseProblems = (definition, types) => {
63
63
  * workflow's tenant's custom steps are step types too, read in the write's transaction, and the custom step versions
64
64
  * a published version uses are kept as wanted, for runners to prepare, until another is published or it is turned off.
65
65
  */
66
- const workflowSaveHook = (schema, types, jobs, consent, custom) => async (event, trx) => {
66
+ const workflowSaveHook = (schema, checkFor, jobs, consent, custom) => async (event, trx) => {
67
67
  if (event.resource.name !== "workflows" || !event.after) return;
68
68
  if (event.operation !== "create" && event.operation !== "update") return;
69
69
  const changed = event.operation === "create" || event.after.version !== event.before?.version;
@@ -71,6 +71,7 @@ const workflowSaveHook = (schema, types, jobs, consent, custom) => async (event,
71
71
  const publishing = enabled !== (event.before?.enabled_version ?? null);
72
72
  if (!changed && !publishing) return;
73
73
  const id = String(event.after.id);
74
+ const types = checkFor(event.after.tenant_id);
74
75
  const check = custom && (changed || enabled !== null) ? withCustomSteps(await custom(trx, event.after.tenant_id)).check(types) : types;
75
76
  if (changed) {
76
77
  refuseProblems(withStepsToCheck(definitionFromParts(event.after)), check);
@@ -1,6 +1,7 @@
1
1
  import { defineJob } from "../../jobs/define-job.js";
2
2
  import { callPlugin, triggerCall } from "./plugin-call.js";
3
3
  import { readyAt, readyWhen, resolveTimeTerms } from "../ready/ready-when.js";
4
+ import { tenantlessMessage } from "../ready/ready-check.js";
4
5
  import { activeTriggers, currentTrigger, triggerFailed } from "./trigger-row.js";
5
6
  import { orRefusal, readyContext, startIfReady } from "../ready/ready-start.js";
6
7
  import { pollJobs } from "./poll-job.js";
@@ -69,6 +70,7 @@ const triggerJobs = (input, text, stop) => {
69
70
  const found = await orRefusal(readyContext(input, trigger));
70
71
  if ("refused" in found) return triggerFailed(db, schema, trigger, "refused", found.refused);
71
72
  if (!found.value) return;
73
+ if (found.value.tenantless !== void 0) return triggerFailed(db, schema, trigger, "no_tenant", found.value.tenantless);
72
74
  const { spec, model, records } = found.value;
73
75
  const split = readyWhen(spec.when);
74
76
  if (!split.ok) return;
@@ -130,10 +132,35 @@ const triggerJobs = (input, text, stop) => {
130
132
  await sql`delete from ${sql.id(schema, "triggers")} where id = ${trigger} and status = 'stopping'`.execute(db);
131
133
  }
132
134
  });
135
+ const tenantless = (trigger) => {
136
+ if (trigger.tenant_id === null) return;
137
+ const spec = input.declared(trigger.type)?.ready(trigger.input);
138
+ const model = spec && input.deps().registry.find(spec.resource)?.model;
139
+ if (!spec || !model || model.tenant) return;
140
+ return tenantlessMessage(spec.resource, input.locale);
141
+ };
142
+ /**
143
+ * Marks each active ready trigger that never fires for want of a tenant field failing, once a minute, so it shows
144
+ * failing soon after the update that removed the field, before any write.
145
+ */
146
+ const tenantCheck = defineJob({
147
+ name: "workflows.trigger-tenant-check",
148
+ schedule: "* * * * *",
149
+ timeout: "1 minute",
150
+ run: async (_, { db }) => {
151
+ const types = [...input.readyTypes];
152
+ if (types.length === 0) return;
153
+ for (const trigger of await activeTriggers(db, schema, types)) {
154
+ const message = trigger.status === "active" ? tenantless(trigger) : void 0;
155
+ if (message) await triggerFailed(db, schema, trigger, "no_tenant", message);
156
+ }
157
+ }
158
+ });
133
159
  /**
134
160
  * Routes each dispatched change to the ready triggers on its resource and tenant: it queues the check of the record at
135
161
  * the time it becomes ready, in the dispatch's transaction. No sweep runs: a record becomes ready by a write, or at a
136
- * time a write set.
162
+ * time a write set. No change reaches a tenant's trigger on a resource without a tenant field, so a change on that
163
+ * resource marks such a trigger failing instead of leaving it active.
137
164
  */
138
165
  const onChanges = async (db, changes) => {
139
166
  const types = [...input.readyTypes];
@@ -145,6 +172,11 @@ const triggerJobs = (input, text, stop) => {
145
172
  const model = spec && input.deps().registry.find(spec.resource)?.model;
146
173
  const split = spec && readyWhen(spec.when);
147
174
  if (!spec || !model || !split?.ok) continue;
175
+ const message = tenantless(trigger);
176
+ if (message) {
177
+ if (trigger.status !== "failing" && changes.some((change) => change.resource === spec.resource)) await triggerFailed(db, schema, trigger, "no_tenant", message);
178
+ continue;
179
+ }
148
180
  const timeTerms = resolveTimeTerms(model, split.when.timeTerms);
149
181
  for (const change of changes) {
150
182
  if (change.resource !== spec.resource || !change.after) continue;
@@ -159,6 +191,7 @@ const triggerJobs = (input, text, stop) => {
159
191
  start,
160
192
  stopJob,
161
193
  readyCheck,
194
+ tenantCheck,
162
195
  ...polls.jobs
163
196
  ],
164
197
  start,
@@ -50,7 +50,7 @@ const workflowEngine = (options, deps, auth, locale, templates = []) => {
50
50
  if (!roles) throw new Error("workflows act on records as each workflow's last editor, with their current roles: give the config `auth` (Better Auth), or `workflows.savedByRoles`");
51
51
  const env = globalThis.process?.env ?? {};
52
52
  const secrets = workflowSecrets(options, env);
53
- const types = workflowTypes(options.plugins, (name) => deps().registry.find(name)?.model, auth?.connectionSupport, templates);
53
+ const types = workflowTypes(options.plugins, (name) => deps().registry.find(name)?.model, auth?.connectionSupport, templates, locale);
54
54
  const appName = shownAppName(auth, env);
55
55
  const mailTemplates = {
56
56
  list: templates,
@@ -84,6 +84,7 @@ const workflowEngine = (options, deps, auth, locale, templates = []) => {
84
84
  deps,
85
85
  schema,
86
86
  roles,
87
+ locale,
87
88
  allowPrivateAddresses,
88
89
  storage,
89
90
  templates: mailTemplates,
@@ -192,7 +193,7 @@ const workflowEngine = (options, deps, auth, locale, templates = []) => {
192
193
  customTypes,
193
194
  customSteps,
194
195
  hooks: [
195
- workflowSaveHook(schema, types.check, triggers, connections.consent, custom),
196
+ workflowSaveHook(schema, types.checkFor, triggers, connections.consent, custom),
196
197
  workflowDeleteHook(schema, triggers),
197
198
  runStartHook(runner, deps, schema),
198
199
  ...storage ? [storageConfigurationHook(storage)] : [],
@@ -1,5 +1,6 @@
1
1
  import { Mailer } from "../mail/mail-message.js";
2
2
  import { ServicesInput } from "./plugin-services.js";
3
+ import { Locale } from "@protobase/schema/internal";
3
4
  import { ResourceModel } from "@protobase/schema";
4
5
  import { CatalogTemplate, CheckOptions, ConnectionSupport, LoadedPlugin, StepWiring, TaskHandlers, TypeEntry } from "@protobase/workflows";
5
6
  import { Plugin, PluginTemplate, PollingTrigger, ReadyTrigger, WebhookTrigger } from "@protobase/workflows/plugin";
@@ -8,17 +9,20 @@ type Models = (name: string) => ResourceModel | undefined;
8
9
  /**
9
10
  * The trigger and step types of an app: the default plugins, then the app's own, all through the same loader and
10
11
  * interface. `types` is the list the MCP tools and the editor read; `check` is what a save checks a definition against,
11
- * the available types only, and `checkWith` the same check against other resources, such as those a caller may read.
12
+ * the available types only, and `checkWith` the same check against other resources, such as those a caller may read;
13
+ * `checkFor` is `check` for a workflow of this tenant, which a ready trigger on a resource without a tenant field never
14
+ * reaches; its words are in the app's `locale`, else English.
12
15
  * A type that signs in is available once the app can make its connection, as `support` says. `app:mail.template`
13
16
  * takes one of `templates`, the app's email templates, by name, its data as that template's schema says;
14
17
  * `templates` lists them as the type list's readers see them.
15
18
  */
16
- export declare const workflowTypes: (loaded?: readonly LoadedPlugin[], models?: Models, support?: ConnectionSupport, mailTemplates?: readonly PluginTemplate[]) => {
19
+ export declare const workflowTypes: (loaded?: readonly LoadedPlugin[], models?: Models, support?: ConnectionSupport, mailTemplates?: readonly PluginTemplate[], locale?: Locale) => {
17
20
  plugins: Plugin[];
18
21
  types: TypeEntry[];
19
22
  templates: CatalogTemplate[];
20
23
  check: CheckOptions;
21
- checkWith: (against: Models) => CheckOptions;
24
+ checkWith: (against: Models, tenanted?: boolean) => CheckOptions;
25
+ checkFor: (tenant: unknown) => CheckOptions;
22
26
  tasks: (input: ServicesInput, mail: Mailer | undefined, connection: StepWiring["connection"], mailbox?: StepWiring["mailbox"]) => TaskHandlers;
23
27
  ready: Map<string, ReadyTrigger>;
24
28
  polling: Map<string, PollingTrigger>;
@@ -1,6 +1,6 @@
1
+ import { readyProblems } from "./ready/ready-check.js";
1
2
  import { workflowPlugins } from "./default-plugins.js";
2
3
  import { pluginServices } from "./plugin-services.js";
3
- import { readyProblems } from "./ready/ready-check.js";
4
4
  import { keyTypes, recordJsonSchema } from "@protobase/schema/internal";
5
5
  import { connectionUnavailable, loadPlugins, stepHandlers, triggerChecks, typeList } from "@protobase/workflows";
6
6
  //#region src/workflows/workflow-types.ts
@@ -31,12 +31,14 @@ const withTemplateNames = (types, names) => names.length === 0 ? types : types.m
31
31
  /**
32
32
  * The trigger and step types of an app: the default plugins, then the app's own, all through the same loader and
33
33
  * interface. `types` is the list the MCP tools and the editor read; `check` is what a save checks a definition against,
34
- * the available types only, and `checkWith` the same check against other resources, such as those a caller may read.
34
+ * the available types only, and `checkWith` the same check against other resources, such as those a caller may read;
35
+ * `checkFor` is `check` for a workflow of this tenant, which a ready trigger on a resource without a tenant field never
36
+ * reaches; its words are in the app's `locale`, else English.
35
37
  * A type that signs in is available once the app can make its connection, as `support` says. `app:mail.template`
36
38
  * takes one of `templates`, the app's email templates, by name, its data as that template's schema says;
37
39
  * `templates` lists them as the type list's readers see them.
38
40
  */
39
- const workflowTypes = (loaded = [], models = () => void 0, support, mailTemplates = []) => {
41
+ const workflowTypes = (loaded = [], models = () => void 0, support, mailTemplates = [], locale) => {
40
42
  const plugins = loadPlugins(workflowPlugins(loaded));
41
43
  const types = withTemplateNames(typeList(plugins, connectionUnavailable(support)), mailTemplates.map((template) => template.name));
42
44
  const templates = mailTemplates.map((template) => ({
@@ -59,13 +61,13 @@ const workflowTypes = (loaded = [], models = () => void 0, support, mailTemplate
59
61
  const steps = types.filter((type) => type.kind === "step" && type.available);
60
62
  const reasons = Object.fromEntries(types.flatMap((type) => type.reason === void 0 ? [] : [[type.id, type.reason]]));
61
63
  const own = triggerChecks(plugins);
62
- const checkWith = (against) => {
64
+ const checkWith = (against, tenanted = false) => {
63
65
  const checks = Object.entries(own).map(([id, check]) => {
64
66
  const declared = ready.get(id);
65
67
  if (!declared) return [id, check];
66
68
  return [id, (input) => {
67
69
  const problems = check(input);
68
- return problems.length > 0 ? problems : readyProblems(against, declared.ready(input));
70
+ return problems.length > 0 ? problems : readyProblems(against, declared.ready(input), tenanted, locale);
69
71
  }];
70
72
  });
71
73
  return {
@@ -86,6 +88,8 @@ const workflowTypes = (loaded = [], models = () => void 0, support, mailTemplate
86
88
  };
87
89
  };
88
90
  const check = checkWith(models);
91
+ const tenantCheck = checkWith(models, true);
92
+ const checkFor = (tenant) => tenant === null || tenant === void 0 ? check : tenantCheck;
89
93
  /** The step types of one segment, which sends mail with the mailer of the job that runs it, signs in through `connection`, and sends from the enabler's `mailbox`. */
90
94
  const tasks = (input, mail, connection, mailbox) => stepHandlers(plugins, {
91
95
  services: pluginServices(input, mail),
@@ -98,6 +102,7 @@ const workflowTypes = (loaded = [], models = () => void 0, support, mailTemplate
98
102
  templates,
99
103
  check,
100
104
  checkWith,
105
+ checkFor,
101
106
  tasks,
102
107
  ready,
103
108
  polling,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/server",
3
- "version": "0.123.5",
3
+ "version": "0.123.6",
4
4
  "description": "The Protobase REST API as a Hono app, with Better Auth sign-in.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -44,11 +44,11 @@
44
44
  "@better-auth/sso": "^1.7.12",
45
45
  "@livekit/protocol": "1.53.1",
46
46
  "@modelcontextprotocol/server": "^2.3.1",
47
- "@protobase/layout": "0.123.5",
48
- "@protobase/query": "0.123.5",
49
- "@protobase/schema": "0.123.5",
50
- "@protobase/workflow-plugins": "0.123.5",
51
- "@protobase/workflows": "0.123.5",
47
+ "@protobase/layout": "0.123.6",
48
+ "@protobase/query": "0.123.6",
49
+ "@protobase/schema": "0.123.6",
50
+ "@protobase/workflow-plugins": "0.123.6",
51
+ "@protobase/workflows": "0.123.6",
52
52
  "@react-email/render": "^2.1.0",
53
53
  "@react-pdf/primitives": "^4.4.0",
54
54
  "@react-pdf/renderer": "^4.9.0",