@tacoshell/sdk 0.0.0-stage → 0.1.1
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/LICENSE +28 -0
- package/README.md +10 -2
- package/package.json +36 -4
- package/src/assets.d.ts +3 -0
- package/src/csv.ts +44 -0
- package/src/index.ts +347 -0
- package/src/zip.ts +56 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
Taco Proprietary License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 ryanrutan. All rights reserved.
|
|
4
|
+
|
|
5
|
+
The software in this repository and in the published packages @tacoshell/sdk,
|
|
6
|
+
@tacoshell/shell and @tacoshell/cli (the "Software") is licensed, not sold.
|
|
7
|
+
|
|
8
|
+
1. Permitted use. You may install the Software and use it to develop, build,
|
|
9
|
+
test, package and distribute your own applications and extensions, including
|
|
10
|
+
the Software's runtime as it is built into those applications. You may also
|
|
11
|
+
read the source code, and modify it for your own use (including your own
|
|
12
|
+
internal forks) to learn from it, debug your applications or adapt it to
|
|
13
|
+
your needs.
|
|
14
|
+
|
|
15
|
+
2. Restrictions. Except as permitted above or by law, you may not: (a) publish
|
|
16
|
+
or distribute the Software or your modified versions of it on their own, or
|
|
17
|
+
as part of any framework, SDK, tool or competing product; (b) sublicense,
|
|
18
|
+
sell, rent or lease the Software; (c) remove or alter any copyright or
|
|
19
|
+
license notice.
|
|
20
|
+
|
|
21
|
+
3. Ownership. The author retains all right, title and interest in the Software.
|
|
22
|
+
No rights are granted other than those expressly stated here.
|
|
23
|
+
|
|
24
|
+
4. No warranty. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
25
|
+
EXPRESS OR IMPLIED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM,
|
|
26
|
+
DAMAGES OR OTHER LIABILITY ARISING FROM THE SOFTWARE OR ITS USE.
|
|
27
|
+
|
|
28
|
+
5. Termination. This license ends automatically if you breach it.
|
package/README.md
CHANGED
|
@@ -1,3 +1,11 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @tacoshell/sdk
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The only import Taco **module code** needs: types and helpers for views, services (`defineService`), dataset routines (`defineRoutine`), topics, notifications, search resolvers and the `Framework` object a view receives.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { defineService, type ViewProps } from '@tacoshell/sdk';
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
Ships TypeScript source (the app build compiles it). You normally don't install this by hand: `taco-cli` brings it, and generated modules type-check against it through `tsconfig.json` paths.
|
|
10
|
+
|
|
11
|
+
Part of the Taco framework monorepo: see the repository root and `dev/GETTING-STARTED.md`.
|
package/package.json
CHANGED
|
@@ -1,6 +1,38 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tacoshell/sdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "The only import Taco module code needs: types and helpers for views, services, topics, search and notifications.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"taco",
|
|
7
|
+
"chrome-extension",
|
|
8
|
+
"mv3",
|
|
9
|
+
"sdk"
|
|
10
|
+
],
|
|
11
|
+
"license": "SEE LICENSE IN LICENSE",
|
|
12
|
+
"repository": {
|
|
13
|
+
"type": "git",
|
|
14
|
+
"url": "git+https://github.com/ryanrutan/tacoshell.git",
|
|
15
|
+
"directory": "packages/sdk"
|
|
16
|
+
},
|
|
17
|
+
"homepage": "https://github.com/ryanrutan/tacoshell#readme",
|
|
18
|
+
"bugs": {
|
|
19
|
+
"url": "https://github.com/ryanrutan/tacoshell/issues"
|
|
20
|
+
},
|
|
21
|
+
"type": "module",
|
|
22
|
+
"exports": {
|
|
23
|
+
".": "./src/index.ts",
|
|
24
|
+
"./package.json": "./package.json"
|
|
25
|
+
},
|
|
26
|
+
"files": [
|
|
27
|
+
"src",
|
|
28
|
+
"README.md",
|
|
29
|
+
"LICENSE"
|
|
30
|
+
],
|
|
31
|
+
"peerDependencies": {
|
|
32
|
+
"react": "^19.0.0"
|
|
33
|
+
},
|
|
34
|
+
"publishConfig": {
|
|
35
|
+
"registry": "https://registry.npmjs.org",
|
|
36
|
+
"access": "public"
|
|
37
|
+
}
|
|
38
|
+
}
|
package/src/assets.d.ts
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// Lets module code import its own CSS (Vite bundles it with the app) and text files as strings (`import sql from './query.sql?raw'`); included by the editor tsconfig taco-cli writes.
|
|
2
|
+
declare module '*.css';
|
|
3
|
+
declare module '*?raw' { const text: string; export default text; }
|
package/src/csv.ts
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// RFC 4180 CSV parse / stringify for module code (the shell has the same logic in core/csv.ts; ADR-045, as CommunityOS lib/csv.js): quoted fields, "" escapes, CRLF or LF, a BOM, embedded newlines.
|
|
2
|
+
|
|
3
|
+
export function parseCsv(text: string): string[][] {
|
|
4
|
+
const rows: string[][] = [];
|
|
5
|
+
let row: string[] = [];
|
|
6
|
+
let field = '';
|
|
7
|
+
let quoted = false;
|
|
8
|
+
const s = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
|
|
9
|
+
for (let i = 0; i < s.length; i++) {
|
|
10
|
+
const ch = s[i];
|
|
11
|
+
if (quoted) {
|
|
12
|
+
if (ch === '"') {
|
|
13
|
+
if (s[i + 1] === '"') { field += '"'; i++; } else quoted = false;
|
|
14
|
+
} else field += ch;
|
|
15
|
+
continue;
|
|
16
|
+
}
|
|
17
|
+
if (ch === '"' && field === '') quoted = true;
|
|
18
|
+
else if (ch === ',') { row.push(field); field = ''; }
|
|
19
|
+
else if (ch === '\n' || ch === '\r') {
|
|
20
|
+
if (ch === '\r' && s[i + 1] === '\n') i++;
|
|
21
|
+
row.push(field); field = '';
|
|
22
|
+
rows.push(row); row = [];
|
|
23
|
+
} else field += ch;
|
|
24
|
+
}
|
|
25
|
+
if (field !== '' || row.length) { row.push(field); rows.push(row); }
|
|
26
|
+
return rows.filter((r) => !(r.length === 1 && r[0] === ''));
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const quote = (v: unknown) => {
|
|
30
|
+
const s = v === null || v === undefined ? '' : typeof v === 'object' ? JSON.stringify(v) : String(v);
|
|
31
|
+
return /[",\r\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
export function stringifyCsv(columns: string[], rows: Record<string, unknown>[]): string {
|
|
35
|
+
return [columns.map(quote).join(','), ...rows.map((r) => columns.map((c) => quote(r[c])).join(','))].join('\r\n') + '\r\n';
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Header row + data rows → objects keyed by the (trimmed) header. */
|
|
39
|
+
export function csvToRows(text: string): Record<string, string>[] {
|
|
40
|
+
const [head, ...rest] = parseCsv(text);
|
|
41
|
+
if (!head) return [];
|
|
42
|
+
const keys = head.map((h) => h.trim());
|
|
43
|
+
return rest.map((cells) => Object.fromEntries(keys.map((k, i) => [k, cells[i] ?? ''])));
|
|
44
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,347 @@
|
|
|
1
|
+
// @tacoshell/sdk: the only framework import module code needs (TECH-GUIDANCE §6).
|
|
2
|
+
export { csvToRows, parseCsv, stringifyCsv } from './csv.ts';
|
|
3
|
+
export { createZip, crc32, downloadFile, type ZipEntry } from './zip.ts';
|
|
4
|
+
import { useEffect, useSyncExternalStore, type ComponentType, type CSSProperties, type ReactNode } from 'react';
|
|
5
|
+
// Generated taco.gen.ts files declare structurally identical ref types inline, so a module also type-checks before this package is installed.
|
|
6
|
+
|
|
7
|
+
// ── References (built by generated code; ADR-020) ────────────────────────────────────────────────────────────────
|
|
8
|
+
|
|
9
|
+
export interface TopicRef<Req, Res> {
|
|
10
|
+
readonly kind: 'topic';
|
|
11
|
+
readonly module: string;
|
|
12
|
+
/** `service:<type>/<name>`, `view:<name>`, `dataset:<name>` or `template:<name>`. */
|
|
13
|
+
readonly component: string;
|
|
14
|
+
readonly topic: string;
|
|
15
|
+
build(payload: Req): Message<Req, Res>;
|
|
16
|
+
}
|
|
17
|
+
export interface Message<Req, Res> { readonly topic: TopicRef<Req, Res>; readonly payload: Req }
|
|
18
|
+
/** `C` is the context the view accepts (declared in its manifest's `context`), so `showView` is type-checked (ADR-052). */
|
|
19
|
+
export interface ViewRef<C = Context> { readonly kind: 'view'; readonly module: string; readonly component: string; readonly __context?: C }
|
|
20
|
+
export interface NotificationPayload { title?: string; message: string; data?: Record<string, unknown>; view?: ViewRef; context?: Record<string, unknown>; key?: string }
|
|
21
|
+
export interface NotificationRef {
|
|
22
|
+
readonly kind: 'notification';
|
|
23
|
+
readonly module: string;
|
|
24
|
+
readonly id: string;
|
|
25
|
+
build(payload: NotificationPayload): NotificationMessage;
|
|
26
|
+
}
|
|
27
|
+
export interface NotificationMessage { readonly notification: NotificationRef; readonly payload: NotificationPayload }
|
|
28
|
+
|
|
29
|
+
export function topic<Req, Res>(module: string, component: string, name: string): TopicRef<Req, Res> {
|
|
30
|
+
const ref: TopicRef<Req, Res> = { kind: 'topic', module, component, topic: name, build: (payload: Req) => ({ topic: ref, payload }) };
|
|
31
|
+
return ref;
|
|
32
|
+
}
|
|
33
|
+
export const view = <C = Context>(module: string, component: string): ViewRef<C> => ({ kind: 'view', module, component });
|
|
34
|
+
export function notification(module: string, id: string): NotificationRef {
|
|
35
|
+
const ref: NotificationRef = { kind: 'notification', module, id, build: (payload) => ({ notification: ref, payload }) };
|
|
36
|
+
return ref;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// ── Logging (ADR-027, ADR-040) ─────────────────────────────────────────────────────────────────────────────────────
|
|
40
|
+
|
|
41
|
+
export type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal';
|
|
42
|
+
export const LOG_LEVELS: readonly LogLevel[] = ['trace', 'debug', 'info', 'warn', 'error', 'fatal'];
|
|
43
|
+
/** Every call returns immediately; nothing waits for the Activity Log (ADR-027). `data` is redacted before storage. */
|
|
44
|
+
export type Logger = Record<LogLevel, (message: string, data?: unknown) => void>;
|
|
45
|
+
|
|
46
|
+
// ── The framework API a view gets (ADR-015, ADR-036) ──────────────────────────────────────────────────────────────
|
|
47
|
+
|
|
48
|
+
export type SendError = 'unavailable' | 'locked' | 'denied' | 'invalid' | 'timeout' | 'failed';
|
|
49
|
+
export type SendResult<Res> = { ok: true; value: Res } | { ok: false; error: SendError; message: string };
|
|
50
|
+
export type Context = Record<string, unknown>;
|
|
51
|
+
|
|
52
|
+
/** An observable value; read it in React with `useStoreValue`. */
|
|
53
|
+
export interface Store<T> { get(): T; subscribe(listener: () => void): () => void }
|
|
54
|
+
|
|
55
|
+
/** Shared by every component on the current page: the view and the panels in its slots (ADR-053). */
|
|
56
|
+
export interface PageContext extends Store<Context> {
|
|
57
|
+
/** Merge values; every component reading the page context re-renders. */
|
|
58
|
+
set(patch: Context): void;
|
|
59
|
+
/** Ask every component on the page to reload its data (e.g. after a write). */
|
|
60
|
+
refresh(reason?: string): void;
|
|
61
|
+
onRefresh(listener: (reason?: string) => void): () => void;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** An entry in the 3rd-level bar's Tools menu, which shows only while the page has tools (ADR-051). */
|
|
65
|
+
export interface Tool {
|
|
66
|
+
id: string;
|
|
67
|
+
label: string;
|
|
68
|
+
/** Font Awesome classes ("fa-solid fa-copy"; the framework bundles Font Awesome Free) or a short text glyph. */
|
|
69
|
+
icon?: string;
|
|
70
|
+
run(): void | Promise<void>;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// ── Feature types, Related, Actions, indicators ──────────────────────────────────────────────────────────────────────
|
|
74
|
+
|
|
75
|
+
/** GENERAL = you build the whole UX; CSV and ITEM standardize one; ACTION opens in a modal over an ITEM; ITEMS is reserved (multi-select ITEM). */
|
|
76
|
+
export type FeatureType = 'GENERAL' | 'CSV' | 'ITEM' | 'ITEMS' | 'ACTION';
|
|
77
|
+
|
|
78
|
+
/** What the framework tells a contributor about the feature being viewed. `href` is relative (`#/v/<module>/<view>`). */
|
|
79
|
+
export interface FeatureInfo { module: string; view: string; /** `<module>/<view>` */ id: string; /** The nav feature the view belongs to. */ feature: string; label: string; type: FeatureType; href: string }
|
|
80
|
+
|
|
81
|
+
/** One entry a feature adds to another feature's Related menu or Actions section. The link to the contributing feature is derived by the framework. */
|
|
82
|
+
export interface Contribution {
|
|
83
|
+
label: string;
|
|
84
|
+
/** Font Awesome classes ("fa-solid fa-copy"). */
|
|
85
|
+
icon?: string;
|
|
86
|
+
/** Extra context for the contributing feature (its own keys). The viewed feature's context always arrives separately as `context.referrer`. */
|
|
87
|
+
context?: Context;
|
|
88
|
+
/** Related only: one small action button beside the link, which launches an ACTION feature in a modal. */
|
|
89
|
+
button?: ContributionButton;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export type ButtonStyleType = 'success' | 'error' | 'info' | 'warn';
|
|
93
|
+
export const BUTTON_LABEL_MAX = 10;
|
|
94
|
+
/**
|
|
95
|
+
* A button on a Related entry. Give one style (all are optional); if several, they layer: `styleType` is the framework's base look (success = green,
|
|
96
|
+
* error = red, info = blue, warn = yellow), `styleClass` (a CSS class of yours) overrides it, and `styleInline` overrides both.
|
|
97
|
+
*/
|
|
98
|
+
export interface ContributionButton {
|
|
99
|
+
/** At most 10 characters (an emoji counts as one); longer text is clipped. */
|
|
100
|
+
label: string;
|
|
101
|
+
styleType?: ButtonStyleType;
|
|
102
|
+
styleClass?: string;
|
|
103
|
+
styleInline?: CSSProperties;
|
|
104
|
+
/** The action's own context (its primary context). The viewed feature's context arrives as `context.referrer`. */
|
|
105
|
+
context?: Context;
|
|
106
|
+
/** The ACTION feature to launch (e.g. `uses.x.view` or `own.views.x.view`). It runs in a modal and may close it with `framework.close()`. */
|
|
107
|
+
action: ViewRef<any>;
|
|
108
|
+
}
|
|
109
|
+
/** `contributeRelated` / `contributeActions`: export one from a view's entry file (and opt in with `related` / `actions` in its manifest). Return nothing to stay out. */
|
|
110
|
+
/** What a contributor may use: the framework as its own module (send to services, storage) and its logger. Reads that need the vault wait for the unlock prompt, so check cheaply first. */
|
|
111
|
+
export interface ContributorEnv { framework: Framework; log: Logger }
|
|
112
|
+
export type Contributor = (feature: FeatureInfo, context: Context, env: ContributorEnv) => Contribution[] | void | Promise<Contribution[] | void>;
|
|
113
|
+
/** The reserved context key: the exact context of the feature the user came from (Related or Actions). */
|
|
114
|
+
export const REFERRER = 'referrer';
|
|
115
|
+
/** Relative URL of a feature (no extension origin). */
|
|
116
|
+
export const featureUrl = (module: string, view: string) => `#/v/${encodeURIComponent(module)}/${encodeURIComponent(view)}`;
|
|
117
|
+
|
|
118
|
+
/** A bubble beside the feature in the left navigation. `text` is at most 4 characters (emoji count as one); colors default from the theme's 16-pair palette. */
|
|
119
|
+
export interface Indicator {
|
|
120
|
+
id: string; text: string; color?: string; background?: string; title?: string;
|
|
121
|
+
/** The feature's view (3rd-level item) this belongs to. It shows on that view's row while the feature is expanded, and rolls up onto the feature's row while collapsed. Without it, it sits on the feature's row. */
|
|
122
|
+
view?: string;
|
|
123
|
+
}
|
|
124
|
+
export interface Indicators {
|
|
125
|
+
add(indicator: Indicator): void;
|
|
126
|
+
update(id: string, patch: Partial<Omit<Indicator, 'id'>>): void;
|
|
127
|
+
remove(id: string): void;
|
|
128
|
+
clear(): void;
|
|
129
|
+
list(): Indicator[];
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export interface BackgroundContext { framework: Framework; log: Logger }
|
|
133
|
+
/** A feature's optional background job (manifest `background: { entry, everySeconds }`). Typically updates `framework.indicators`. */
|
|
134
|
+
export interface BackgroundJob { run(ctx: BackgroundContext): Promise<void> | void }
|
|
135
|
+
export const defineBackground = (job: BackgroundJob): BackgroundJob => job;
|
|
136
|
+
|
|
137
|
+
export type RowStatus = 'ok' | 'warn' | 'error';
|
|
138
|
+
export interface RowResult { status: RowStatus; message?: string }
|
|
139
|
+
export interface CsvColumn { key: string; label?: string; /** Example value for the generated template. */ sample?: string; /** The upload must have this column. */ required?: boolean; /** false = kept in the row sent to the processor but not shown (default true). */ show?: boolean }
|
|
140
|
+
export interface CsvRowContext { framework: Framework; index: number; total: number; log: Logger }
|
|
141
|
+
export interface CsvFeatureDef {
|
|
142
|
+
kind: 'csv';
|
|
143
|
+
columns: CsvColumn[];
|
|
144
|
+
/** Overrides the one-row template built from `columns[].sample`. */
|
|
145
|
+
template?: { filename?: string; rows?: Record<string, string>[] };
|
|
146
|
+
intro?: string;
|
|
147
|
+
/** Return a problem to reject the whole file (listed in the Activity Log). */
|
|
148
|
+
validateRow?(row: Record<string, string>, line: number): string | null;
|
|
149
|
+
/** Return a reason to drop the row before the preview (logged with its line number). */
|
|
150
|
+
skipRow?(row: Record<string, string>, line: number): string | null;
|
|
151
|
+
confirm: { title?: string; steps: string[]; warning?: string };
|
|
152
|
+
processLabel?: string;
|
|
153
|
+
/** Pause between rows. */
|
|
154
|
+
delayMs?: number;
|
|
155
|
+
/** Receives the full CSV row. Throwing counts as 'error'. */
|
|
156
|
+
processRow(row: Record<string, string>, ctx: CsvRowContext): Promise<RowStatus | RowResult> | RowStatus | RowResult;
|
|
157
|
+
}
|
|
158
|
+
export const defineCsvFeature = (def: Omit<CsvFeatureDef, 'kind'>): CsvFeatureDef => ({ kind: 'csv', ...def });
|
|
159
|
+
|
|
160
|
+
export interface ItemFeatureDef {
|
|
161
|
+
kind: 'item';
|
|
162
|
+
/** The main pane: whatever you want. */
|
|
163
|
+
leftPane: ComponentType<ViewProps>;
|
|
164
|
+
/** Right rail (400px) above / below the framework's Actions section; leave out to not show. */
|
|
165
|
+
rightRailHeader?: ComponentType<ViewProps>;
|
|
166
|
+
rightRailFooter?: ComponentType<ViewProps>;
|
|
167
|
+
}
|
|
168
|
+
export const defineItemFeature = (def: Omit<ItemFeatureDef, 'kind'>): ItemFeatureDef => ({ kind: 'item', ...def });
|
|
169
|
+
export type FeatureDef = CsvFeatureDef | ItemFeatureDef;
|
|
170
|
+
|
|
171
|
+
/** One of this module's datasets, live. */
|
|
172
|
+
export interface DatasetInfo {
|
|
173
|
+
name: string; label: string; kind: 'importOnly' | 'refreshable'; key?: string; rows: number; columns: string[];
|
|
174
|
+
/** ISO time of the last refresh or import. */
|
|
175
|
+
updatedAt?: string; source?: 'csv' | 'routine' | 'set';
|
|
176
|
+
refreshing: boolean; /** What the running refresh says it is doing (`ctx.progress`). */ progress?: string; cancelling: boolean;
|
|
177
|
+
/** Plain-English schedule ("Manual only", "Every day at 2:00 AM"). */
|
|
178
|
+
schedule: string; lastError?: string;
|
|
179
|
+
/** Declared `incremental: true`, and which load the next refresh will do. */
|
|
180
|
+
incremental: boolean; load: 'full' | 'incremental';
|
|
181
|
+
}
|
|
182
|
+
export interface DatasetsApi extends Store<DatasetInfo[]> {
|
|
183
|
+
/** Refresh one of this module's datasets (queued behind any refresh already running); `load: 'full'` forces a Full Load. */
|
|
184
|
+
refresh(name: string, opts?: { load?: 'full' | 'incremental' }): Promise<SendResult<DatasetInfo>>;
|
|
185
|
+
/** Ask the running refresh to stop (its routine sees `ctx.signal`). */
|
|
186
|
+
cancel(name: string): void;
|
|
187
|
+
}
|
|
188
|
+
/** What a Settings tab component receives (ADR-072). */
|
|
189
|
+
export interface SettingsTabProps { framework: Framework }
|
|
190
|
+
|
|
191
|
+
export interface Framework {
|
|
192
|
+
/** This module's datasets, live, with refresh and cancel: what a Settings → Datasets tab is built from. */
|
|
193
|
+
datasets: DatasetsApi;
|
|
194
|
+
/** Declare what this feature is showing now. It is the `context` Related and Actions contributors receive (empty until you call it). */
|
|
195
|
+
expose(context: Context): void;
|
|
196
|
+
/** Add, update and remove this feature's indicator bubbles in the left navigation (also from its background job). */
|
|
197
|
+
indicators: Indicators;
|
|
198
|
+
/** Relative URL of a feature: `urlOf(feature)` or `urlOf(viewRef)`. */
|
|
199
|
+
urlOf(target: FeatureInfo | ViewRef<any>): string;
|
|
200
|
+
/** Closes this view when it is shown as an ACTION modal; does nothing elsewhere. Call it when the action is done and needs no further user interaction (a quick action that renders nothing never shows its modal). */
|
|
201
|
+
close(): void;
|
|
202
|
+
/** Request/response to a topic (a service operation, a dataset query…). Never throws; check `ok`. */
|
|
203
|
+
send<Req, Res>(message: Message<Req, Res>): Promise<SendResult<Res>>;
|
|
204
|
+
/** Fire an event topic to every subscriber. */
|
|
205
|
+
publish<Req>(message: Message<Req, unknown>): void;
|
|
206
|
+
subscribe<Req>(topic: TopicRef<Req, unknown>, handler: (payload: Req) => void): () => void;
|
|
207
|
+
/** Navigate with state. Resolves false if a guard refused or the context doesn't match the view's declaration (ADR-036, ADR-052). */
|
|
208
|
+
showView<C>(view: ViewRef<C>, context?: C): Promise<boolean>;
|
|
209
|
+
/** The latest context this view was given: at open time, then any later hand-off while it is open (ADR-052). */
|
|
210
|
+
viewContext: Store<Context | undefined>;
|
|
211
|
+
/** State shared by every component on this page (ADR-053). */
|
|
212
|
+
page: PageContext;
|
|
213
|
+
/** Add to the 3rd-level bar's Tools menu for as long as this page is open; returns a function that removes it. */
|
|
214
|
+
tools: { add(tool: Tool): () => void };
|
|
215
|
+
/** Renders the panels other modules contribute to one of this view's declared slots (ADR-053). */
|
|
216
|
+
slot(name: string): ReactNode;
|
|
217
|
+
/** Send a declared notification (ADR-028, ADR-041). */
|
|
218
|
+
notify(message: NotificationMessage): void;
|
|
219
|
+
log: Logger;
|
|
220
|
+
/** Navigation guards; each returns a function that removes the guard. */
|
|
221
|
+
guard: {
|
|
222
|
+
/** Refuse every navigation while held (e.g. a bulk run). */
|
|
223
|
+
block(reason: string): () => void;
|
|
224
|
+
/** Ask Stay / Leave while `isDirty()` is true. */
|
|
225
|
+
unsaved(isDirty: () => boolean): () => void;
|
|
226
|
+
};
|
|
227
|
+
/** Encrypted storage scoped to this module (ADR-031). Waits for the unlock prompt while the vault is locked. */
|
|
228
|
+
storage: { get<T>(key: string): Promise<T | undefined>; set(key: string, value: unknown): Promise<void>; remove(key: string): Promise<void> };
|
|
229
|
+
/** Receive context handed over by `showView` while this view is open (ADR-036). Prefer `useViewContext`. */
|
|
230
|
+
setContextHandler(handler: (context: Context) => void): void;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// ── React hooks ────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
234
|
+
|
|
235
|
+
export const useStoreValue = <T,>(store: Store<T>): T => useSyncExternalStore(store.subscribe, store.get);
|
|
236
|
+
/** The context this view was opened with, updated live when another view hands it a new one. */
|
|
237
|
+
export const useViewContext = <C = Context,>(framework: Framework) => useStoreValue(framework.viewContext) as C | undefined;
|
|
238
|
+
/** The page's shared state; re-renders when any component on the page changes it. */
|
|
239
|
+
export const usePageContext = <C = Context,>(framework: Framework) => useStoreValue(framework.page) as C;
|
|
240
|
+
/** Runs `reload` whenever a component on the page calls `framework.page.refresh()` or the user presses Refresh in the 3rd-level bar. A page with no listener is re-mounted by that button instead. */
|
|
241
|
+
export function usePageRefresh(framework: Framework, reload: (reason?: string) => void) {
|
|
242
|
+
useEffect(() => framework.page.onRefresh(reload), [framework, reload]);
|
|
243
|
+
}
|
|
244
|
+
/** This module's datasets, re-rendering as they refresh. */
|
|
245
|
+
export const useDatasets = (framework: Framework) => useStoreValue(framework.datasets);
|
|
246
|
+
/** Keeps what Related and Actions contributors see in step with `context` while mounted. */
|
|
247
|
+
export function useExposeContext(framework: Framework, context: Context) {
|
|
248
|
+
const key = JSON.stringify(context);
|
|
249
|
+
useEffect(() => framework.expose(context), [framework, key]);
|
|
250
|
+
}
|
|
251
|
+
/** Adds a Tools menu entry while the component is mounted. */
|
|
252
|
+
export function useTool(framework: Framework, tool: Tool | null) {
|
|
253
|
+
useEffect(() => (tool ? framework.tools.add(tool) : undefined), [framework, tool?.id]);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** A panel contributed into another view's slot (ADR-053). It reads and writes the host page's context through `framework.page`. */
|
|
257
|
+
export interface PanelProps { framework: Framework; slot: string }
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* A card: a sub-feature any page can show. It is wired to page-context entries (manifest › cards.<name>.context), not to a page: it appears on every view
|
|
261
|
+
* whose page context has them and works the same on each. `context` holds just those entries and updates live; `framework.page` is the host page's.
|
|
262
|
+
*/
|
|
263
|
+
export interface CardProps<C = Context> { framework: Framework; context: C }
|
|
264
|
+
|
|
265
|
+
export interface ViewProps {
|
|
266
|
+
framework: Framework;
|
|
267
|
+
/** Context the view was opened with, if any. Later contexts arrive through `setContextHandler`. */
|
|
268
|
+
context?: Context;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// ── Services (ADR-004, ADR-023) ────────────────────────────────────────────────────────────────────────────────────
|
|
272
|
+
|
|
273
|
+
export interface ServiceContext {
|
|
274
|
+
instance: { module: string; type: string; name: string };
|
|
275
|
+
/** Non-secret field values from Settings → Services (a field's declared `default` fills in when it is empty). Features read them with the standard `config` topic. */
|
|
276
|
+
config: Record<string, string>;
|
|
277
|
+
authMode: 'session' | 'apikey' | 'basic' | 'oauth' | 'none';
|
|
278
|
+
/** A secret field from the vault. Waits for the unlock prompt while the vault is locked. */
|
|
279
|
+
secret(field: string): Promise<string>;
|
|
280
|
+
/**
|
|
281
|
+
* https-only fetch limited to the service's declared hosts, with the auth mode applied (cookies for session, headers otherwise)
|
|
282
|
+
* and one redacted debug log line per attempt (ADR-040). `json` sets a JSON body.
|
|
283
|
+
*/
|
|
284
|
+
fetch(url: string, init?: RequestInit & { json?: unknown }): Promise<Response>;
|
|
285
|
+
log: Logger;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** One thing a search term resolved to. `context` is the connector's own description of it (e.g. `{ slug, email }`); Quick Actions receive it. */
|
|
289
|
+
export interface SearchResult { id: string; label: string; detail?: string; context: Context }
|
|
290
|
+
|
|
291
|
+
export interface ServiceImpl {
|
|
292
|
+
/**
|
|
293
|
+
* Opt-in search (declare `resolver` on the service in taco.module.json): turn the header search term into zero or more contexts.
|
|
294
|
+
* One result is used as the context without asking; several are listed for the user to pick. Views then offer Quick Action tiles for it.
|
|
295
|
+
*/
|
|
296
|
+
resolve?(term: string, ctx: ServiceContext): Promise<SearchResult[]>;
|
|
297
|
+
/**
|
|
298
|
+
* For "Current Session" sign-in: is the user signed in to the service's site right now? Shown in the header's Sessions menu.
|
|
299
|
+
* Return `{ active: false }` (or throw) when there is no session. If you leave this out, a passing `test()` counts as an active session.
|
|
300
|
+
*/
|
|
301
|
+
session?(ctx: ServiceContext): Promise<{ active: boolean; who?: string; detail?: string }>;
|
|
302
|
+
/**
|
|
303
|
+
* Re-establish the session: the Sessions menu offers "Sign in again" on a service whose `session()` says it isn't active and that implements this
|
|
304
|
+
* (open the provider's sign-in, or ask a local bridge to run `gcloud auth login`). Throw to report why it failed; the menu re-checks afterwards.
|
|
305
|
+
* A service with `auth: ["none"]` and a `sessionRequirement` is listed in the Sessions menu too: it reports its own status with `session()`.
|
|
306
|
+
*/
|
|
307
|
+
reauth?(ctx: ServiceContext): Promise<void>;
|
|
308
|
+
/**
|
|
309
|
+
* The Test button on the service page: your script that proves the saved configuration works. Throw to fail (red). Return `who` to show "Connected as …",
|
|
310
|
+
* or `status: 'warn'` (with `detail`) when it works but something needs attention (yellow), e.g. the token is fine but a configured board isn't reachable.
|
|
311
|
+
*/
|
|
312
|
+
test?(ctx: ServiceContext): Promise<{ who?: string; status?: 'ok' | 'warn'; detail?: string } | void>;
|
|
313
|
+
/**
|
|
314
|
+
* Your own authentication for `ctx.fetch`: return the headers to send. When present it replaces the auth mode's built-in header (e.g. Trello wants
|
|
315
|
+
* `Authorization: OAuth oauth_consumer_key="<key>", oauth_token="<token>"` built from two credentials). Read credentials with `ctx.secret(field)` and `ctx.config`.
|
|
316
|
+
*/
|
|
317
|
+
authorize?(ctx: ServiceContext): Promise<Record<string, string>> | Record<string, string>;
|
|
318
|
+
/** Handlers for the service's custom topics (declared in taco.module.json). */
|
|
319
|
+
topics?: Record<string, (payload: any, ctx: ServiceContext) => Promise<unknown>>;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
export const defineService = (impl: ServiceImpl): ServiceImpl => impl;
|
|
323
|
+
|
|
324
|
+
// ── Dataset routines (ADR-043): how a refreshable dataset produces its rows ─────────────────────────────────────────
|
|
325
|
+
|
|
326
|
+
export interface RoutineContext {
|
|
327
|
+
/** The module's framework instance: call services through `send` (uses / own constants), like any view. */
|
|
328
|
+
framework: Framework;
|
|
329
|
+
log: Logger;
|
|
330
|
+
previous: { rows: number; updatedAt?: string };
|
|
331
|
+
/**
|
|
332
|
+
* 'full' replaces everything; 'incremental' (only for a dataset declared `incremental: true`, once it has data) means load just what changed since
|
|
333
|
+
* `previous.updatedAt` and return `mode: 'append'` or `'upsert'`. The user can switch a dataset to a Full Load.
|
|
334
|
+
*/
|
|
335
|
+
load: 'full' | 'incremental';
|
|
336
|
+
/** Say what the refresh is doing ("Signing in…", "Running query…"): shown on Settings → Datasets and the header icon while it runs. */
|
|
337
|
+
progress(message: string): void;
|
|
338
|
+
/** Aborted when the user cancels the refresh. Stop and throw (or return); anything you return after a cancel is discarded. */
|
|
339
|
+
signal: AbortSignal;
|
|
340
|
+
}
|
|
341
|
+
/** What a routine returns. `replace` (default) swaps all rows; `append` adds them; `upsert` adds or updates by the dataset's key. Stored data changes only when the routine succeeds. */
|
|
342
|
+
export interface RoutineResult { rows: Record<string, unknown>[]; columns?: string[]; mode?: 'replace' | 'append' | 'upsert' }
|
|
343
|
+
export interface Routine {
|
|
344
|
+
/** Produces the rows (a Full Load returns every row). A failed or cancelled refresh loses nothing. */
|
|
345
|
+
run(ctx: RoutineContext): Promise<RoutineResult>;
|
|
346
|
+
}
|
|
347
|
+
export const defineRoutine = (routine: Routine): Routine => routine;
|
package/src/zip.ts
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// A small ZIP writer (stored entries, no compression) for things a module hands the user: a setup bundle, an export. Dependency-free (CommunityOS ADR-068 / Taco ADR-045).
|
|
2
|
+
|
|
3
|
+
const TABLE = (() => { const t = new Uint32Array(256); for (let n = 0; n < 256; n++) { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; t[n] = c >>> 0; } return t; })();
|
|
4
|
+
/** CRC-32 (the ZIP / PNG polynomial) of some bytes. */
|
|
5
|
+
export function crc32(bytes: Uint8Array): number {
|
|
6
|
+
let c = 0xffffffff;
|
|
7
|
+
for (let i = 0; i < bytes.length; i++) c = TABLE[(c ^ bytes[i]) & 0xff] ^ (c >>> 8);
|
|
8
|
+
return (c ^ 0xffffffff) >>> 0;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface ZipEntry {
|
|
12
|
+
/** Path inside the ZIP, "/" separated ("bridge/dataset-bridge.py"). End with "/" for a folder. */
|
|
13
|
+
name: string;
|
|
14
|
+
data?: string | Uint8Array;
|
|
15
|
+
/** Unix permissions (0o755 for a script that must be executable); default 0o644. */
|
|
16
|
+
mode?: number;
|
|
17
|
+
modified?: Date;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const dosTime = (d: Date) => ((d.getHours() << 11) | (d.getMinutes() << 5) | (d.getSeconds() >> 1)) & 0xffff;
|
|
21
|
+
const dosDate = (d: Date) => ((Math.max(0, d.getFullYear() - 1980) << 9) | ((d.getMonth() + 1) << 5) | d.getDate()) & 0xffff;
|
|
22
|
+
|
|
23
|
+
/** Builds a ZIP file (stored, UTF-8 names, unix modes kept) from entries. */
|
|
24
|
+
export function createZip(entries: ZipEntry[]): Uint8Array {
|
|
25
|
+
const enc = new TextEncoder();
|
|
26
|
+
const chunks: Uint8Array[] = [];
|
|
27
|
+
const central: Uint8Array[] = [];
|
|
28
|
+
let offset = 0;
|
|
29
|
+
const u16 = (v: number) => [v & 0xff, (v >>> 8) & 0xff];
|
|
30
|
+
const u32 = (v: number) => [v & 0xff, (v >>> 8) & 0xff, (v >>> 16) & 0xff, (v >>> 24) & 0xff];
|
|
31
|
+
for (const e of entries) {
|
|
32
|
+
const name = enc.encode(e.name);
|
|
33
|
+
const data = typeof e.data === 'string' ? enc.encode(e.data) : e.data ?? new Uint8Array(0);
|
|
34
|
+
const crc = crc32(data), when = e.modified ?? new Date(), isDir = e.name.endsWith('/');
|
|
35
|
+
const mode = e.mode ?? (isDir ? 0o755 : 0o644);
|
|
36
|
+
const header = Uint8Array.from([...u32(0x04034b50), ...u16(20), ...u16(0x0800), ...u16(0), ...u16(dosTime(when)), ...u16(dosDate(when)), ...u32(crc), ...u32(data.length), ...u32(data.length), ...u16(name.length), ...u16(0)]);
|
|
37
|
+
chunks.push(header, name, data);
|
|
38
|
+
central.push(Uint8Array.from([...u32(0x02014b50), ...u16((3 << 8) | 20), ...u16(20), ...u16(0x0800), ...u16(0), ...u16(dosTime(when)), ...u16(dosDate(when)), ...u32(crc), ...u32(data.length), ...u32(data.length), ...u16(name.length), ...u16(0), ...u16(0), ...u16(0), ...u16(0), ...u32(((isDir ? 0o040000 : 0o100000) | mode) * 0x10000 + (isDir ? 0x10 : 0)), ...u32(offset)]), name);
|
|
39
|
+
offset += header.length + name.length + data.length;
|
|
40
|
+
}
|
|
41
|
+
const centralSize = central.reduce((n, c) => n + c.length, 0);
|
|
42
|
+
const end = Uint8Array.from([...u32(0x06054b50), ...u16(0), ...u16(0), ...u16(entries.length), ...u16(entries.length), ...u32(centralSize), ...u32(offset), ...u16(0)]);
|
|
43
|
+
const all = [...chunks, ...central, end];
|
|
44
|
+
const out = new Uint8Array(all.reduce((n, c) => n + c.length, 0));
|
|
45
|
+
let p = 0;
|
|
46
|
+
for (const c of all) { out.set(c, p); p += c.length; }
|
|
47
|
+
return out;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Offers bytes or text to the user as a file download (in a browser page). */
|
|
51
|
+
export function downloadFile(name: string, data: string | Uint8Array, mime = 'application/octet-stream') {
|
|
52
|
+
const url = URL.createObjectURL(new Blob([data as BlobPart], { type: mime }));
|
|
53
|
+
const a = Object.assign(document.createElement('a'), { href: url, download: name });
|
|
54
|
+
a.click();
|
|
55
|
+
setTimeout(() => URL.revokeObjectURL(url), 10_000);
|
|
56
|
+
}
|