@palettelab/cli 0.3.57 → 0.3.59
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/README.md +52 -2
- package/backend-sdk/palette_sdk/__init__.py +3 -1
- package/backend-sdk/palette_sdk/organization.py +50 -0
- package/backend-sdk/palette_sdk/plugin_context.py +7 -0
- package/backend-sdk/palette_sdk/services.py +23 -4
- package/docs/python-backend-sdk.md +6 -1
- package/lib/cli.js +4 -1
- package/lib/commands/dev.js +2 -0
- package/lib/commands/update.js +65 -0
- package/lib/update-check.js +172 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -4,6 +4,20 @@ Developer CLI for building plugins for the Palette platform. Works without any a
|
|
|
4
4
|
|
|
5
5
|
The installed executable is `pltt`.
|
|
6
6
|
|
|
7
|
+
## API Surface Split
|
|
8
|
+
|
|
9
|
+
Use the right helper for the runtime you are coding in:
|
|
10
|
+
|
|
11
|
+
| Runtime | Package/helper | Use it for |
|
|
12
|
+
|---|---|---|
|
|
13
|
+
| Frontend TypeScript/React | `@palettelab/sdk`, `createPaletteClient(...)`, `palette.*` | UI code, current-user OS APIs, frontend broker clients, Data Room browsing/upload from the browser, toasts, and current-user OS notifications |
|
|
14
|
+
| Backend Python/FastAPI | `palette_sdk`, `PluginContext`, `ctx.*`, `services(ctx)` | Backend routes, permission gates, app-owned data, migrations, cross-user notifications, server-side Data Rooms, managed services, app-to-app service handlers, and lifecycle hooks |
|
|
15
|
+
| CLI tooling | `pltt ...` | Scaffolding, local dev, testing, packaging, publishing, hosted sandbox previews, and generating frontend/backend typed service clients |
|
|
16
|
+
|
|
17
|
+
The CLI bundles `palette_sdk` for local backend simulation, but backend app
|
|
18
|
+
code should import `palette_sdk`, not `@palettelab/sdk`. Frontend app code
|
|
19
|
+
should import `@palettelab/sdk`, not `palette_sdk`.
|
|
20
|
+
|
|
7
21
|
## Requirements
|
|
8
22
|
|
|
9
23
|
- Node.js 18+
|
|
@@ -28,6 +42,12 @@ pltt version
|
|
|
28
42
|
pltt --version
|
|
29
43
|
```
|
|
30
44
|
|
|
45
|
+
Update a global install with:
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
pltt update
|
|
49
|
+
```
|
|
50
|
+
|
|
31
51
|
## Quick Start: Build And Test A Palette App
|
|
32
52
|
|
|
33
53
|
Use this flow when a developer wants to create an app, run it locally, then test
|
|
@@ -44,6 +64,12 @@ npx --yes @palettelab/cli@latest dev
|
|
|
44
64
|
backend, manifest, SDK hooks, and local database checks. It does not require
|
|
45
65
|
Docker and does not publish anything to the platform.
|
|
46
66
|
|
|
67
|
+
For interactive runs, `pltt dev`, `pltt sandbox`, and `pltt preview` check
|
|
68
|
+
whether a newer `@palettelab/cli` version is available on npm. The check is
|
|
69
|
+
non-blocking, cached for 24 hours, skipped for `--json` and CI, and ignored if
|
|
70
|
+
npm registry access is unavailable. Set `PLTT_UPDATE_CHECK=0` to disable the
|
|
71
|
+
notice.
|
|
72
|
+
|
|
47
73
|
When the app is ready to test with real Palette OS services, configure a hosted
|
|
48
74
|
sandbox environment and run:
|
|
49
75
|
|
|
@@ -337,7 +363,12 @@ async def sync_invoices(ctx: PluginContext = Depends(get_plugin_context)):
|
|
|
337
363
|
|
|
338
364
|
Storage upload responses include both snake_case and camelCase aliases for object metadata (`object_path`/`objectPath`, `file_url`/`fileUrl`, `content_type`/`contentType`) so local simulator and hosted OS responses can be consumed with the same app code.
|
|
339
365
|
|
|
340
|
-
App storage is different from Data Room uploads.
|
|
366
|
+
App storage is different from Data Room uploads. Backend Python code uses
|
|
367
|
+
`ctx.storage`; frontend TypeScript code uses `palette.storage`. Both write
|
|
368
|
+
app-owned files directly to the OS-configured storage backend, currently GCS in
|
|
369
|
+
hosted environments. Use backend `ctx.data_rooms` or frontend
|
|
370
|
+
`palette.dataRooms` only when the file should be managed as a Data Room
|
|
371
|
+
document.
|
|
341
372
|
|
|
342
373
|
Python backend app-storage example:
|
|
343
374
|
|
|
@@ -746,6 +777,24 @@ pltt version --json
|
|
|
746
777
|
pltt --version
|
|
747
778
|
```
|
|
748
779
|
|
|
780
|
+
### `pltt update`
|
|
781
|
+
|
|
782
|
+
Update the `pltt` CLI when it is installed globally through npm.
|
|
783
|
+
|
|
784
|
+
```bash
|
|
785
|
+
pltt update
|
|
786
|
+
pltt update --json
|
|
787
|
+
```
|
|
788
|
+
|
|
789
|
+
When the current executable was launched through `npx`, `npm exec`, or a local
|
|
790
|
+
source checkout, `pltt update` does not force a global install. It prints the
|
|
791
|
+
current/latest versions and the correct command instead:
|
|
792
|
+
|
|
793
|
+
```bash
|
|
794
|
+
npx --yes @palettelab/cli@latest <command>
|
|
795
|
+
npm install -g @palettelab/cli@latest
|
|
796
|
+
```
|
|
797
|
+
|
|
749
798
|
### `pltt doctor`
|
|
750
799
|
|
|
751
800
|
Check local tooling and common setup problems.
|
|
@@ -910,10 +959,11 @@ they are easier to review and reuse for generated clients.
|
|
|
910
959
|
|
|
911
960
|
## Global Flags
|
|
912
961
|
|
|
913
|
-
- `--json` emits machine-readable output for `package`, `publish`, `status`, `logs`, `test`, and `version`.
|
|
962
|
+
- `--json` emits machine-readable output for `package`, `publish`, `status`, `logs`, `test`, `update`, and `version`.
|
|
914
963
|
- `-v, --version` prints the installed `pltt` CLI version.
|
|
915
964
|
- `--env <name>` selects a configured publish/status/logs environment.
|
|
916
965
|
- `-y, --yes` skips production publish confirmation.
|
|
966
|
+
- `PLTT_UPDATE_CHECK=0` disables the non-blocking npm update notice shown by interactive dev commands.
|
|
917
967
|
|
|
918
968
|
## What gets shipped
|
|
919
969
|
|
|
@@ -7,6 +7,7 @@ from palette_sdk.connections import ConnectionStatus, MissingConnectionError, Pl
|
|
|
7
7
|
from palette_sdk.apps import AppInteropClient, AppServiceClient, MissingAppServiceError
|
|
8
8
|
from palette_sdk.members import OrganizationMembersClient
|
|
9
9
|
from palette_sdk.notifications import NotificationRecipient, NotificationsClient
|
|
10
|
+
from palette_sdk.organization import OrganizationInfo
|
|
10
11
|
from palette_sdk.platform_services import (
|
|
11
12
|
LocalRedisService,
|
|
12
13
|
LocalVectorService,
|
|
@@ -64,6 +65,7 @@ __all__ = [
|
|
|
64
65
|
"AppServiceClient",
|
|
65
66
|
"MissingAppServiceError",
|
|
66
67
|
"OrganizationMembersClient",
|
|
68
|
+
"OrganizationInfo",
|
|
67
69
|
"NotificationsClient",
|
|
68
70
|
"NotificationRecipient",
|
|
69
71
|
"LocalRedisService",
|
|
@@ -110,4 +112,4 @@ __all__ = [
|
|
|
110
112
|
"LocalStorageService",
|
|
111
113
|
]
|
|
112
114
|
|
|
113
|
-
__version__ = "0.1.
|
|
115
|
+
__version__ = "0.1.10"
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""Organisation info exposed to plugin backend code via ``ctx.organization``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import asdict, dataclass
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass(frozen=True)
|
|
10
|
+
class OrganizationInfo:
|
|
11
|
+
"""Read-only snapshot of the calling organisation.
|
|
12
|
+
|
|
13
|
+
Injected by the platform runtime on every request, so values reflect the
|
|
14
|
+
organisation's current settings (name, logo, company type, ...). All
|
|
15
|
+
fields are ``None`` when running outside an organisation context.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
id: int | None = None
|
|
19
|
+
name: str | None = None
|
|
20
|
+
slug: str | None = None
|
|
21
|
+
description: str | None = None
|
|
22
|
+
company_type: str | None = None
|
|
23
|
+
logo_url: str | None = None
|
|
24
|
+
theme_id: str | None = None
|
|
25
|
+
created_at: str | None = None
|
|
26
|
+
updated_at: str | None = None
|
|
27
|
+
|
|
28
|
+
@property
|
|
29
|
+
def category(self) -> str | None:
|
|
30
|
+
"""Alias for :attr:`company_type`."""
|
|
31
|
+
return self.company_type
|
|
32
|
+
|
|
33
|
+
@classmethod
|
|
34
|
+
def from_dict(cls, data: dict[str, Any] | None) -> "OrganizationInfo":
|
|
35
|
+
if not isinstance(data, dict):
|
|
36
|
+
return cls()
|
|
37
|
+
return cls(
|
|
38
|
+
id=data.get("id"),
|
|
39
|
+
name=data.get("name"),
|
|
40
|
+
slug=data.get("slug"),
|
|
41
|
+
description=data.get("description"),
|
|
42
|
+
company_type=data.get("company_type"),
|
|
43
|
+
logo_url=data.get("logo_url"),
|
|
44
|
+
theme_id=data.get("theme_id"),
|
|
45
|
+
created_at=data.get("created_at"),
|
|
46
|
+
updated_at=data.get("updated_at"),
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
def to_dict(self) -> dict[str, Any]:
|
|
50
|
+
return asdict(self)
|
|
@@ -15,6 +15,7 @@ from palette_sdk.connections import PluginConnectionsClient
|
|
|
15
15
|
from palette_sdk.apps import AppInteropClient
|
|
16
16
|
from palette_sdk.members import OrganizationMembersClient
|
|
17
17
|
from palette_sdk.notifications import NotificationsClient
|
|
18
|
+
from palette_sdk.organization import OrganizationInfo
|
|
18
19
|
from palette_sdk.platform_services import UnavailablePlatformService
|
|
19
20
|
from palette_sdk.events import EventPublisher
|
|
20
21
|
|
|
@@ -36,6 +37,10 @@ class PluginContext:
|
|
|
36
37
|
organization_id = ?` — RLS already does it.
|
|
37
38
|
user_id: UUID of the authenticated user
|
|
38
39
|
organization_id: Current org ID
|
|
40
|
+
organization: Read-only snapshot of the current organisation's
|
|
41
|
+
settings (name, slug, logo_url, company_type, description, ...).
|
|
42
|
+
Refreshed on every request, so it always reflects the latest
|
|
43
|
+
values saved in Settings -> Organisation.
|
|
39
44
|
org_role: User's role in the org (owner/admin/member)
|
|
40
45
|
plugin_id: The plugin's ID from its manifest
|
|
41
46
|
permissions: List of permissions declared in the manifest
|
|
@@ -46,6 +51,7 @@ class PluginContext:
|
|
|
46
51
|
db: AsyncSession
|
|
47
52
|
user_id: str
|
|
48
53
|
organization_id: int
|
|
54
|
+
organization: OrganizationInfo = field(default_factory=OrganizationInfo)
|
|
49
55
|
org_role: str | None = None
|
|
50
56
|
plugin_id: str = ""
|
|
51
57
|
permissions: list[str] = field(default_factory=list)
|
|
@@ -117,6 +123,7 @@ async def get_plugin_context(request: Request) -> PluginContext:
|
|
|
117
123
|
db=state.db,
|
|
118
124
|
user_id=str(state.user.id),
|
|
119
125
|
organization_id=state.user.organization_id,
|
|
126
|
+
organization=OrganizationInfo.from_dict(getattr(state, "organization_info", None)),
|
|
120
127
|
org_role=getattr(state, "org_role", None),
|
|
121
128
|
plugin_id=getattr(state, "plugin_id", ""),
|
|
122
129
|
permissions=getattr(state, "plugin_permissions", []),
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"""OS-broker service helpers
|
|
1
|
+
"""OS-broker service helpers — provider + consumer side.
|
|
2
2
|
|
|
3
3
|
Provider example::
|
|
4
4
|
|
|
@@ -46,6 +46,9 @@ class ServiceDecl:
|
|
|
46
46
|
replacement: str | None = None
|
|
47
47
|
|
|
48
48
|
|
|
49
|
+
# Plugin-declared service handlers captured during module import. The platform
|
|
50
|
+
# drains this list after loading each plugin and registers them with the broker
|
|
51
|
+
# under the plugin's namespace/version.
|
|
49
52
|
_pending: list[ServiceDecl] = []
|
|
50
53
|
|
|
51
54
|
|
|
@@ -94,6 +97,8 @@ def drain_pending_services() -> list[ServiceDecl]:
|
|
|
94
97
|
return out
|
|
95
98
|
|
|
96
99
|
|
|
100
|
+
# ----- Consumer accessor -----------------------------------------------------------
|
|
101
|
+
|
|
97
102
|
class BrokerCallError(RuntimeError):
|
|
98
103
|
"""Raised when the broker rejects or fails a service call."""
|
|
99
104
|
|
|
@@ -107,7 +112,11 @@ class CrossAppGrantError(BrokerCallError):
|
|
|
107
112
|
|
|
108
113
|
|
|
109
114
|
class ServicesClient:
|
|
110
|
-
"""Returned by `services(ctx)`. Use `.call(target, payload)` or sugar `.proxy(...)`.
|
|
115
|
+
"""Returned by `services(ctx)`. Use `.call(target, payload)` or sugar `.proxy(...)`.
|
|
116
|
+
|
|
117
|
+
The proxy form lets you write `client.proxy("org/v1").members.list({...})`
|
|
118
|
+
for nicer-looking call sites once codegen produces typed stubs.
|
|
119
|
+
"""
|
|
111
120
|
|
|
112
121
|
def __init__(self, adapter: Any | None):
|
|
113
122
|
self._adapter = adapter
|
|
@@ -130,7 +139,11 @@ class ServicesClient:
|
|
|
130
139
|
|
|
131
140
|
|
|
132
141
|
class _Proxy:
|
|
133
|
-
"""Dotted-attribute syntax
|
|
142
|
+
"""Dotted-attribute syntax → broker target string.
|
|
143
|
+
|
|
144
|
+
Example: `client.proxy("org/v1").members.list(payload)` →
|
|
145
|
+
`client.call("org/v1#members.list", payload)`.
|
|
146
|
+
"""
|
|
134
147
|
|
|
135
148
|
def __init__(self, client: ServicesClient, namespace_version: str, segments: tuple[str, ...] = ()):
|
|
136
149
|
if "/" not in namespace_version:
|
|
@@ -150,9 +163,15 @@ class _Proxy:
|
|
|
150
163
|
|
|
151
164
|
|
|
152
165
|
def services(ctx_or_adapter: Any) -> ServicesClient:
|
|
153
|
-
"""Resolve a `ServicesClient` from either a `PluginContext` or an adapter.
|
|
166
|
+
"""Resolve a `ServicesClient` from either a `PluginContext` or an adapter.
|
|
167
|
+
|
|
168
|
+
The accessor accepts the runtime `PluginContext` directly (most common) or
|
|
169
|
+
any object exposing `broker_call`/`broker_emit`.
|
|
170
|
+
"""
|
|
154
171
|
if ctx_or_adapter is None:
|
|
155
172
|
return ServicesClient(None)
|
|
173
|
+
# PluginContext path: `ctx.apps` is an `AppInteropClient` that wraps the
|
|
174
|
+
# platform adapter and forwards `broker_call`/`broker_emit`.
|
|
156
175
|
apps = getattr(ctx_or_adapter, "apps", None)
|
|
157
176
|
if apps is not None and hasattr(apps, "broker_call"):
|
|
158
177
|
return ServicesClient(apps)
|
|
@@ -881,7 +881,12 @@ Example mock:
|
|
|
881
881
|
}
|
|
882
882
|
```
|
|
883
883
|
|
|
884
|
-
App storage is separate from Data Rooms.
|
|
884
|
+
App storage is separate from Data Rooms. Backend Python code uses
|
|
885
|
+
`ctx.storage`; frontend TypeScript code uses `palette.storage`. Both write
|
|
886
|
+
app-owned files directly to the OS-configured storage backend, currently GCS in
|
|
887
|
+
hosted environments. Use backend `ctx.data_rooms` or frontend
|
|
888
|
+
`palette.dataRooms` only when the file should be visible and governed as a Data
|
|
889
|
+
Room document.
|
|
885
890
|
|
|
886
891
|
Palette scopes storage the same way. Files written through `ctx.storage` or the
|
|
887
892
|
frontend storage client live under:
|
package/lib/cli.js
CHANGED
|
@@ -13,6 +13,7 @@ const logs = require("./commands/logs")
|
|
|
13
13
|
const secrets = require("./commands/secrets")
|
|
14
14
|
const services = require("./commands/services")
|
|
15
15
|
const version = require("./commands/version")
|
|
16
|
+
const update = require("./commands/update")
|
|
16
17
|
|
|
17
18
|
const COMMANDS = {
|
|
18
19
|
init: { run: init, help: "Scaffold a new plugin directory from the template" },
|
|
@@ -57,6 +58,7 @@ const COMMANDS = {
|
|
|
57
58
|
help: "Inspect / pull / scaffold OS-broker services (list, pull, scaffold)",
|
|
58
59
|
},
|
|
59
60
|
version: { run: version, help: "Show the installed pltt CLI version" },
|
|
61
|
+
update: { run: update, help: "Update the globally installed pltt CLI" },
|
|
60
62
|
}
|
|
61
63
|
|
|
62
64
|
function printHelp() {
|
|
@@ -67,7 +69,7 @@ function printHelp() {
|
|
|
67
69
|
console.log(` ${name.padEnd(8)} ${help}`)
|
|
68
70
|
}
|
|
69
71
|
console.log("\nGlobal flags:")
|
|
70
|
-
console.log(" --json Emit machine-readable JSON output (status, logs, package, publish, test, version)")
|
|
72
|
+
console.log(" --json Emit machine-readable JSON output (status, logs, package, publish, test, update, version)")
|
|
71
73
|
console.log(" -v, --version Show the installed pltt CLI version")
|
|
72
74
|
console.log("\nPublish flags:")
|
|
73
75
|
console.log(" --env <name> Target environment from ~/.palette/config.json (default: local)")
|
|
@@ -105,6 +107,7 @@ function printHelp() {
|
|
|
105
107
|
console.log(" pltt package")
|
|
106
108
|
console.log(" pltt publish --env staging")
|
|
107
109
|
console.log(" pltt status")
|
|
110
|
+
console.log(" pltt update")
|
|
108
111
|
console.log(" pltt logs --follow")
|
|
109
112
|
console.log(" pltt secrets init")
|
|
110
113
|
}
|
package/lib/commands/dev.js
CHANGED
|
@@ -12,6 +12,7 @@ const { loadLocalEnvDetails } = require("../secrets")
|
|
|
12
12
|
const buildCommand = require("./build")
|
|
13
13
|
const publish = require("./publish")
|
|
14
14
|
const logs = require("./logs")
|
|
15
|
+
const { notifyIfUpdateAvailable } = require("../update-check")
|
|
15
16
|
|
|
16
17
|
const DEFAULT_PLATFORM_IMAGE = "ghcr.io/palette-lab/platform-dev:latest"
|
|
17
18
|
const DEFAULT_IMAGE = process.env.PALETTE_DEV_IMAGE || DEFAULT_PLATFORM_IMAGE
|
|
@@ -127,6 +128,7 @@ function writePlatformEnvFile(cwd, localEnv) {
|
|
|
127
128
|
}
|
|
128
129
|
|
|
129
130
|
async function run(args, { cwd }) {
|
|
131
|
+
notifyIfUpdateAvailable(args).catch(() => {})
|
|
130
132
|
const { flags, rest } = parseFlags(args)
|
|
131
133
|
const cloud = rest.includes("--cloud") || rest.includes("--sandbox")
|
|
132
134
|
const platform = rest.includes("--platform")
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"use strict"
|
|
2
|
+
|
|
3
|
+
const { spawnSync } = require("child_process")
|
|
4
|
+
const {
|
|
5
|
+
PACKAGE_NAME,
|
|
6
|
+
checkForUpdate,
|
|
7
|
+
detectGlobalInstall,
|
|
8
|
+
} = require("../update-check")
|
|
9
|
+
|
|
10
|
+
function printInstallHint(info) {
|
|
11
|
+
console.log(`[pltt] installed: ${info.current}`)
|
|
12
|
+
if (info.latest) {
|
|
13
|
+
console.log(`[pltt] latest: ${info.latest}`)
|
|
14
|
+
} else {
|
|
15
|
+
console.log("[pltt] latest: unavailable")
|
|
16
|
+
}
|
|
17
|
+
console.log("")
|
|
18
|
+
console.log("[pltt] this CLI does not look like a global npm install.")
|
|
19
|
+
console.log(` To run the latest version without installing: npx --yes ${PACKAGE_NAME}@latest <command>`)
|
|
20
|
+
console.log(` To install globally: npm install -g ${PACKAGE_NAME}@latest`)
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
async function run(args = []) {
|
|
24
|
+
const json = args.includes("--json")
|
|
25
|
+
const info = await checkForUpdate({ force: true }).catch(() => ({
|
|
26
|
+
name: PACKAGE_NAME,
|
|
27
|
+
current: require("../../package.json").version,
|
|
28
|
+
latest: null,
|
|
29
|
+
updateAvailable: false,
|
|
30
|
+
source: "unavailable",
|
|
31
|
+
}))
|
|
32
|
+
const install = detectGlobalInstall()
|
|
33
|
+
|
|
34
|
+
if (json) {
|
|
35
|
+
console.log(
|
|
36
|
+
JSON.stringify({
|
|
37
|
+
...info,
|
|
38
|
+
globalInstall: install.global,
|
|
39
|
+
packageRoot: install.packageRoot,
|
|
40
|
+
globalPackageRoot: install.globalPackageRoot,
|
|
41
|
+
}),
|
|
42
|
+
)
|
|
43
|
+
return
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
if (!install.global) {
|
|
47
|
+
printInstallHint(info)
|
|
48
|
+
return
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
if (info.latest && !info.updateAvailable) {
|
|
52
|
+
console.log(`[pltt] ${PACKAGE_NAME} is already up to date (${info.current}).`)
|
|
53
|
+
return
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
console.log(`[pltt] updating ${PACKAGE_NAME} with npm install -g ${PACKAGE_NAME}@latest`)
|
|
57
|
+
const res = spawnSync("npm", ["install", "-g", `${PACKAGE_NAME}@latest`], {
|
|
58
|
+
stdio: "inherit",
|
|
59
|
+
})
|
|
60
|
+
if (res.status !== 0) {
|
|
61
|
+
process.exit(res.status || 1)
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
module.exports = run
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
"use strict"
|
|
2
|
+
|
|
3
|
+
const fs = require("fs")
|
|
4
|
+
const os = require("os")
|
|
5
|
+
const path = require("path")
|
|
6
|
+
const { spawnSync } = require("child_process")
|
|
7
|
+
const pkg = require("../package.json")
|
|
8
|
+
|
|
9
|
+
const PACKAGE_NAME = pkg.name
|
|
10
|
+
const REGISTRY_URL = `https://registry.npmjs.org/${encodeURIComponent(PACKAGE_NAME)}/latest`
|
|
11
|
+
const CACHE_TTL_MS = 24 * 60 * 60 * 1000
|
|
12
|
+
|
|
13
|
+
function cachePath() {
|
|
14
|
+
return path.join(os.homedir(), ".palette", "pltt-update-check.json")
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function normalizeVersion(version) {
|
|
18
|
+
return String(version || "")
|
|
19
|
+
.trim()
|
|
20
|
+
.replace(/^v/, "")
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function versionParts(version) {
|
|
24
|
+
return normalizeVersion(version)
|
|
25
|
+
.split("-", 1)[0]
|
|
26
|
+
.split(".")
|
|
27
|
+
.map((part) => Number.parseInt(part, 10))
|
|
28
|
+
.map((part) => (Number.isFinite(part) ? part : 0))
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function compareVersions(left, right) {
|
|
32
|
+
const a = versionParts(left)
|
|
33
|
+
const b = versionParts(right)
|
|
34
|
+
const len = Math.max(a.length, b.length, 3)
|
|
35
|
+
for (let i = 0; i < len; i++) {
|
|
36
|
+
const av = a[i] || 0
|
|
37
|
+
const bv = b[i] || 0
|
|
38
|
+
if (av > bv) return 1
|
|
39
|
+
if (av < bv) return -1
|
|
40
|
+
}
|
|
41
|
+
return 0
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function readCache(now = Date.now()) {
|
|
45
|
+
try {
|
|
46
|
+
const file = cachePath()
|
|
47
|
+
if (!fs.existsSync(file)) return null
|
|
48
|
+
const data = JSON.parse(fs.readFileSync(file, "utf8"))
|
|
49
|
+
if (!data || typeof data !== "object") return null
|
|
50
|
+
if (!data.checked_at || now - Number(data.checked_at) > CACHE_TTL_MS) return null
|
|
51
|
+
return data
|
|
52
|
+
} catch {
|
|
53
|
+
return null
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function writeCache(data) {
|
|
58
|
+
try {
|
|
59
|
+
const file = cachePath()
|
|
60
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 })
|
|
61
|
+
fs.writeFileSync(file, `${JSON.stringify(data, null, 2)}\n`, { mode: 0o600 })
|
|
62
|
+
} catch {
|
|
63
|
+
// Update checks should never make the CLI command fail.
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async function fetchLatestVersion({ fetchImpl = globalThis.fetch } = {}) {
|
|
68
|
+
if (typeof fetchImpl !== "function") return null
|
|
69
|
+
const res = await fetchImpl(REGISTRY_URL, {
|
|
70
|
+
headers: { Accept: "application/json", "User-Agent": `${PACKAGE_NAME}/${pkg.version}` },
|
|
71
|
+
})
|
|
72
|
+
if (!res.ok) return null
|
|
73
|
+
const data = await res.json()
|
|
74
|
+
return normalizeVersion(data.version)
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
async function checkForUpdate({ force = false, fetchImpl, now = Date.now() } = {}) {
|
|
78
|
+
const current = normalizeVersion(pkg.version)
|
|
79
|
+
const cached = force ? null : readCache(now)
|
|
80
|
+
let latest = cached && cached.latest
|
|
81
|
+
let source = cached ? "cache" : "registry"
|
|
82
|
+
|
|
83
|
+
if (!latest) {
|
|
84
|
+
latest = await fetchLatestVersion({ fetchImpl })
|
|
85
|
+
if (!latest) {
|
|
86
|
+
return { name: PACKAGE_NAME, current, latest: null, updateAvailable: false, source: "unavailable" }
|
|
87
|
+
}
|
|
88
|
+
writeCache({ checked_at: now, name: PACKAGE_NAME, current, latest })
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
return {
|
|
92
|
+
name: PACKAGE_NAME,
|
|
93
|
+
current,
|
|
94
|
+
latest,
|
|
95
|
+
updateAvailable: compareVersions(latest, current) > 0,
|
|
96
|
+
source,
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function updateCheckDisabled(env = process.env) {
|
|
101
|
+
const value = String(env.PLTT_UPDATE_CHECK || "").trim().toLowerCase()
|
|
102
|
+
return value === "0" || value === "false" || value === "off" || value === "no"
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function shouldNotify(args = [], env = process.env, stream = process.stderr) {
|
|
106
|
+
if (args.includes("--json")) return false
|
|
107
|
+
if (env.CI) return false
|
|
108
|
+
if (updateCheckDisabled(env)) return false
|
|
109
|
+
if (!stream || !stream.isTTY) return false
|
|
110
|
+
return true
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function formatUpdateNotice(info) {
|
|
114
|
+
return (
|
|
115
|
+
`[pltt] update available: ${info.current} -> ${info.latest}\n` +
|
|
116
|
+
" Run `pltt update` to update the CLI.\n"
|
|
117
|
+
)
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function notifyIfUpdateAvailable(args = [], options = {}) {
|
|
121
|
+
const stream = options.stream || process.stderr
|
|
122
|
+
if (!shouldNotify(args, options.env || process.env, stream)) return Promise.resolve(null)
|
|
123
|
+
|
|
124
|
+
return checkForUpdate(options)
|
|
125
|
+
.then((info) => {
|
|
126
|
+
if (info.updateAvailable) stream.write(formatUpdateNotice(info))
|
|
127
|
+
return info
|
|
128
|
+
})
|
|
129
|
+
.catch(() => null)
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function packageRoot() {
|
|
133
|
+
return path.resolve(__dirname, "..")
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function realpathIfExists(target) {
|
|
137
|
+
try {
|
|
138
|
+
return fs.realpathSync(target)
|
|
139
|
+
} catch {
|
|
140
|
+
return null
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function detectGlobalInstall({ spawn = spawnSync } = {}) {
|
|
145
|
+
const npmRoot = spawn("npm", ["root", "-g"], { encoding: "utf8" })
|
|
146
|
+
if (npmRoot.status !== 0 || !npmRoot.stdout) {
|
|
147
|
+
return { global: false, reason: "npm-root-failed", packageRoot: packageRoot(), globalPackageRoot: null }
|
|
148
|
+
}
|
|
149
|
+
const globalPackageRoot = path.join(npmRoot.stdout.trim(), "@palettelab", "cli")
|
|
150
|
+
const installed = realpathIfExists(packageRoot())
|
|
151
|
+
const globalInstalled = realpathIfExists(globalPackageRoot)
|
|
152
|
+
return {
|
|
153
|
+
global: Boolean(installed && globalInstalled && installed === globalInstalled),
|
|
154
|
+
reason: installed && globalInstalled ? "checked" : "path-missing",
|
|
155
|
+
packageRoot: installed || packageRoot(),
|
|
156
|
+
globalPackageRoot,
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
module.exports = {
|
|
161
|
+
CACHE_TTL_MS,
|
|
162
|
+
PACKAGE_NAME,
|
|
163
|
+
REGISTRY_URL,
|
|
164
|
+
cachePath,
|
|
165
|
+
checkForUpdate,
|
|
166
|
+
compareVersions,
|
|
167
|
+
detectGlobalInstall,
|
|
168
|
+
formatUpdateNotice,
|
|
169
|
+
notifyIfUpdateAvailable,
|
|
170
|
+
shouldNotify,
|
|
171
|
+
updateCheckDisabled,
|
|
172
|
+
}
|